How does free know the size of memory to be deleted.?, C/C++ Programming

How does free know the size of memory to be deleted.?

int *i = (int *)malloc(12); followed by free(i); how did free function call know how much of memory to delete?

A: It based on the implementation, however usually there is a malloc header added to all the memory allocated through malloc. On Linux its four bytes of memory preceding the memory returned to you, which contain the number of bytes allocated + 4(itself). Thus while you say,

int *i = (int *)malloc(12);

it allocates 16 bytes.

-------------------

17 | | | |

-------------------

^

|

i

Since you can see above total of 16 bytes are allocated, first four bytes stores the number of bytes allocated(offset to the next memory from the begin of this memory). Address of the 5th byte is returned to i. now i can access 12 bytes through this byte.

Posted Date: 3/19/2013 8:25:49 AM | Location : United States







Related Discussions:- How does free know the size of memory to be deleted.?, Assignment Help, Ask Question on How does free know the size of memory to be deleted.?, Get Answer, Expert's Help, How does free know the size of memory to be deleted.? Discussions

Write discussion on How does free know the size of memory to be deleted.?
Your posts are moderated
Related Questions
Write a program to find the area under the curve y = f(x) between x = a and x = b, integrate y = f(x) between the limits of a and b. The area under a curve betw .

Addition of array elements: #define rows 3 #define cols 3 void main() {                 int i=0,j=0,sum=0;                 int arr[rows][cols];



accept principal amount,rate of interest, & duration from the user. display interest amount and total amount

how to create program in c that will system restart

Compiler Design - Limit In The Method Instructions


Byteland county is very famous for luminous jewels. Luminous jewels are used in making beautiful necklaces. A necklace consists of various luminous jewels of particular colour. Nec

What is the difference among const char *myPointer and char *const myPointer?  A: Const char *myPointer is a non constant pointer to constant data; whereas char *const myPointer