假设有 20 个内存块,并且指针 p
指向第一个 block 。
现在,当我这样做时:
p++;
free(p);
将释放多少内存块以及为什么?
最佳答案
不确定性。不能说。您需要提供 malloc()
返回的确切指针。
传递一个指向 free()
的指针,该指针不是由 malloc()
[及其家族]返回的 undefined behaviour .
根据您的问题,如果 malloc()
-ed 指针存储在 p
中,并且您执行 p++
并调用 free(p);
,那么 p
不再是 由 calloc
返回的指针>、malloc
或 realloc
函数。
根据 c99
标准第 7.20.3.2 章第 2 段
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
关于c - C语言中如果改变指针会释放多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27876923/