S
Stephan Beal
Hello group!
i'm currently working on code where i find myself repeatedly having to
allocating two objects to store some private data, e.g.:
whio_stream * whio_stream_for_dev( struct whio_dev * dev, bool
takeOwnership )
{
if( ! dev ) return 0;
whio_stream * str = (whio_stream*)malloc( sizeof(whio_stream) );
if( ! str ) return 0;
*str = whio_stream_dev_init;
whio_stream_dev * sd = (whio_stream_dev*) (str + sizeof
(whio_stream));
if( ! sd )
{
free(str);
return 0;
}
str->implData = sd;
sd->dev = dev;
sd->ownsDev = takeOwnership;
return str;
}
The significant bit there is the two mallocs. Today i figured i'd try
to consolidate that, and turned the above code into:
whio_stream * whio_stream_for_dev( struct whio_dev * dev, bool
takeOwnership )
{
if( ! dev ) return 0;
whio_stream * str = (whio_stream*)malloc( sizeof(whio_stream) +
sizeof(whio_stream_dev) );
if( ! str ) return 0;
*str = whio_stream_dev_init;
whio_stream_dev * sd = (whio_stream_dev*) (str + sizeof
(whio_stream));
str->implData = sd;
sd->dev = dev;
sd->ownsDev = takeOwnership;
return str;
}
and i changed my cleanup routine to not free the sd object (since free
(str) will now free that). That "seems to work", but now to my
question:
Is that second approach safe or am i just asking for alignment-related
(or platform-specific) problems?
If it is NOT safe, can you recommend a portable workaround which will
achieve the goal of using only one malloc instead of two?
Many thanks in advance for your insights!
i'm currently working on code where i find myself repeatedly having to
allocating two objects to store some private data, e.g.:
whio_stream * whio_stream_for_dev( struct whio_dev * dev, bool
takeOwnership )
{
if( ! dev ) return 0;
whio_stream * str = (whio_stream*)malloc( sizeof(whio_stream) );
if( ! str ) return 0;
*str = whio_stream_dev_init;
whio_stream_dev * sd = (whio_stream_dev*) (str + sizeof
(whio_stream));
if( ! sd )
{
free(str);
return 0;
}
str->implData = sd;
sd->dev = dev;
sd->ownsDev = takeOwnership;
return str;
}
The significant bit there is the two mallocs. Today i figured i'd try
to consolidate that, and turned the above code into:
whio_stream * whio_stream_for_dev( struct whio_dev * dev, bool
takeOwnership )
{
if( ! dev ) return 0;
whio_stream * str = (whio_stream*)malloc( sizeof(whio_stream) +
sizeof(whio_stream_dev) );
if( ! str ) return 0;
*str = whio_stream_dev_init;
whio_stream_dev * sd = (whio_stream_dev*) (str + sizeof
(whio_stream));
str->implData = sd;
sd->dev = dev;
sd->ownsDev = takeOwnership;
return str;
}
and i changed my cleanup routine to not free the sd object (since free
(str) will now free that). That "seems to work", but now to my
question:
Is that second approach safe or am i just asking for alignment-related
(or platform-specific) problems?
If it is NOT safe, can you recommend a portable workaround which will
achieve the goal of using only one malloc instead of two?
Many thanks in advance for your insights!