#include <stdio.h>
#include <stdlib.h>
int main(){
int * ptr = (int*)malloc(sizeof(int)*100); // Allocated space for 100 integers
// Some code
free(ptr); // Calling free with ptr as argument
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何释放所有 400 字节(在我的例子中)?ptr仅包含内存中一个字节的地址,而且我没有传递任何其他参数来指定动态数组的大小,以便它可以运行循环并释放所有字节
如果我这样做会发生什么:
ptr++;
free(ptr);
Run Code Online (Sandbox Code Playgroud)
既然我们无法通过给出指针来检索堆中数组的大小,那么这意味着malloc()不知道保留了多少字节,ptr那么为什么它不从前一个数组的中间开始分配另一个堆内存呢?