Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

Memory allocation usin malloc

Hi Experts,

I am experimenting with how memory is allocated on the heap.  It appears, when I do malloc back to back, the first one returns an address in one page, and the second one returns an address in another page(4096 bytes page size).  I was expecting( most likely incorrectly) that it will be in the same page, but would be separated by the allocation table data.  Does every malloc goes and fetch addresses from different pages?
Thank you.


        int i, j;

	int * firstArray = malloc(sizeof(int)*20);
	int *secondArray = malloc(sizeof(int)*10);
	for( j = 0; j < 5; j++)
	{
		secondArray[j] = 11;
	}
	for( i = 0; i < 25; i++)
	{
		firstArray[i] = 10;
	}

Open in new window

Avatar of jkr
jkr
Flag of Germany image

Yup, the 'usual' algorithms for allocating on the heap will either a) rely on undelying OS code or b) offer a scheme where it is most worthwile to fragment the heap as least as possible. So, in your case, the allocator code might have found regions that are better suitable to place your request in other than two consecutive pieces of memory (yet that might happen as well). As a bottom line, assumptions about what heap allocators return are futile at best, better not worry about that in the first place.
Avatar of ambuli

ASKER

sure:-) i was curious as to why it is allocated on a new page. thank you. one more question. I believe the allocation info is usually placed in the block before or after the allocated block. how much of memory is used for this data and what information is stored there. is there any reference doc for this.
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 ambuli

ASKER

thanks.  i was studying about heap corruptions and that is why i was interested in.
As a 'real life' example - I had to design an allocator for a UDF2 file system for real time video recording, and *speed* therefore was the primary  factor - so, find the first slot that satisfies your requirements and move on... (in hindsight, I see much room for optimization ;o)