Here's a simple C code, what does malloc and free do?
[CPP]View Plaincopy
- int main ()
- {
- char* p = (char*) malloc (32);
- Free (p);
- return 0;
- }
The debug and release versions of malloc and free have different implementations and vary greatly.
Debug version
malloc needs to allocate more than 36byte more memory than the actual size. The final allocated memory block is as follows: _crtmemblockheader is a doubly linked list structure, which is defined as follows:
[CPP]View Plaincopy
- <pre name="code" class="CPP" >typedef struct _crtmemblockheader
- {
- struct _crtmemblockheader *pblockheadernext; //Next allocated block of memory
- struct _crtmemblockheader *pblockheaderprev; //Last allocated block of memory
- Char *szfilename; //Allocate the file name of the memory code
- int nLine; //Allocate the line number of the memory code
- size_t ndatasize; The size of the request, as in the instance
- int nblockuse; //requested memory type, such as the user type in the instance
- long lrequest; //Request ID, each request will be logged
- unsigned char gap[nnomanslandsize]; //4 byte check digit
- } _crtmemblockheader;
The user requests the memory to have 4 bytes of check digit before and after allocating memory, which will be initialized to 0xFD. If the 8 bytes are overwritten, the assertion failure is triggered when free. The requested 32 bytes are initialized to 0xCC (as with the initialization of the stack). The system can display errors by recording this information. For example, the memory of the cross-border access request fails to assert under Debug, and the release below does not, which can cause a huge hidden danger to the program. Many of the occasional errors in release are created in this way. _crtmemblockheader A total of 32 bytes, plus a user-requested 32-byte and last 4-byte check bit is 68 bytes. The final call to the system's API requests memory. For example, Windows below is HeapAlloc.
If the memory allocation fails, malloc does not call New_handler as new, and it returns null directly. Free is the _crtmemblockheader of the information to do cleanup operations, checking the check bit and so on. Finally, the system API is called to free memory. For example, Windows below is HeapFree.
Release version
the actual allocated memory equals the requested memory size. malloc and free simply make some judgments on top of the system API.
Summarize
The
C language is cross-platform and the final memory processing is done to the system API. The system records the address, size, release, and so on for each piece of allocated memory. So it is only necessary to pass an address parameter for free. And the same address cannot be freed two times.
http://blog.csdn.net/passion_wu128/article/details/38964045
C Language malloc and free implementation principles