c - C语言中如果改变指针会释放多少内存?

标签 c memory free

假设有 20 个内存块,并且指针 p 指向第一个 block 。 现在,当我这样做时:

p++;
free(p);

将释放多少内存块以及为什么?

最佳答案

不确定性。不能说。您需要提供 malloc() 返回的确切指针。

传递一个指向 free() 的指针,该指针不是由 malloc() [及其家族]返回的 undefined behaviour .

根据您的问题,如果 malloc()-ed 指针存储在 p 中,并且您执行 p++ 并调用 free(p);,那么 p 不再是 calloc 返回的指针>、mallocrealloc 函数。

根据 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/

相关文章:

看不懂这些 :free immediately after malloc;close file immediately after open

iOS 核心数据怎么会泄露?

c - 在调用 free() 时使用符号 (&)

c - 当我们 malloc() 时,我们真的必须 free() 吗?那么它与自动变量有什么不同呢?

C代码setjmp声明函数?

c - 执行未从 exec 返回

c - 如何在不接触缓存的情况下写入或读取内存

c - 关于 C 中的静态和共享库链接

c - 从串口读取数据

c - malloc 之后的空闲内存分配