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(st ruct 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(s truct mystruct)+padding) using malloc or is the extra memory allocation handled by the compiler?
thanks
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(st
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
delete[] p; //Executes the destructor for each object in the 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.