Link to home
Start Free TrialLog in
Avatar of LuckyLucks
LuckyLucks

asked on

malloc and padding

Hi

I have a question - If the memory I am reading back seems to be padded to make it aligned to byte boundaries, who is responsible to make sure that sufficient memory was allocated when the writing  took place initially.

For example,, i wrote a series of structs. When i read back i allocated number_of_struct*sizeof(struct mystruct) using malloc. However on looking through the memory returned to me, i find it padded. Was i supposed to allocate  number_of_struct*(sizeof(struct mystruct)+padding) using malloc or is the extra memory allocation handled by the compiler?

thanks
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HooKooDooKu
HooKooDooKu

First of all, you're question should become mute if you use the C++ malloc operator known as 'new'.  If you need an array of mystruct, just simply create a new array...

mystruct* p = new mystruct[5]; //Creates 5 new 'mystruct' object in an array

Otherwise, I think so that pointers and arrays would work... the sizeof() operator should account for any padding that goes into a 'mystruct' object.  Therefore you could alternately do the following:
mystruct* p = malloc( sizeof( mystruct ) * 5 );
That should get you the memory you need.  But your structure will not be initialized.  By contrast, if you use the 'new' operator, the constructor for the 5 mystruct objects will get executed.
BTW, 'delete' is the opposite of 'new', and if you have an array, you don't delete each object in the array, you simply use the delete array syntax:

delete[] p; //Executes the destructor for each object in the array