본문 바로가기

개발

The concept of malloc, free function

The concept of malloc, free function


As you know, we can use malloc function when we allocate memory dynamically.
In my case, I just know that malloc function allocate memory in heap segment.
I didn’t know about principle of malloc function, so I would like to introduce malloc function principal.
Definition : void *malloc (size_t size);
We can use that like below.

char *ptr1 = (char *)malloc (100 * sizeof (char));
char *ptr2 = (char *)malloc (130 * sizeof(char));

Then, the memory is allocated like below picture.
If we use malloc function, the extra memory control block is created internally.
The memory control block is just the structure like below.

Struct mcb
{
	Int size;
	Int isAvailable;
}

the memory control block size is 8(32 bit system) bytes.
So the size is the allocated memory size and memory control block size.
The ‘isAvailable’ variable is important.
In case of ‘1’, the meaning is not available.
In case of ‘0’, the meaning is available.
That means, if we allocate memory, then ‘isAvailable’ value is ‘1’.
If we release the memory by free function, ‘isAvailable’ variable value change ‘0’.
Please, below to refer.

free (ptr);

Then, we have to assign ‘null’ value to ‘ptr1’variable.

ptr1 = null;

In Conclusion When malloc() allocate memory in heap segment, the memory control block is created, internally. Free () just change ‘isAvailable’ value in memory control block. So sometimes *ptr can access value but that is bug.
반응형

'개발' 카테고리의 다른 글

Successfully installed Caffe framework without GPU on my macbook pro  (0) 2015.10.21
JCO ~ 자바 컨퍼런스!!!  (0) 2012.02.17
endl of C++  (0) 2010.02.17
__cplusplus_4  (0) 2009.08.12
ISP mode error  (0) 2009.08.06