当我们调用内存管理函数(malloc、calloc 或 realloc)时,这些函数会保留额外的字节用于簿记。
每当调用 free()
函数并传递指向已分配内存的指针时,free()
函数都会获取簿记信息并释放分配的内存。 无论如何,如果程序更改指向已分配地址的指针的值,则调用 free()
函数会给出未定义的结果。
____ The allocated block ____
/ \
+--------+--------------------+
| Header | Your data area ... |
+--------+--------------------+
^
|
+-- Returned Address
示例代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *pcBuffer = NULL;
pcBuffer = malloc(sizeof(char) * 16); //Allocate the memory
pcBuffer++; //Increment the pointer
free(pcBuffer); //Call free function to release the allocated memory
return 0;
}