如果在 C 中更改指针会释放多少内存? [英] How much memory would be freed if pointer is changed in C?
问题描述
假设有 20 个内存块,并且一个指针 p
指向第一个块.现在,当我这样做时:
Let's say there are 20 blocks of memory and a pointer p
is pointing to the first block.
Now, when I do:
p++;
free(p);
将释放多少内存块以及为什么?
How many blocks of memory would be freed and why?
推荐答案
不确定.不能说.您需要提供由 malloc()
返回的确切指针.
Un-deterministic. Cannot say. You need to supply the exact pointer which was returned by malloc()
.
将一个指向 free()
的指针传递给 malloc()
[和 family] 没有返回的指针是 未定义的行为.
Passing a pointer to free()
which is not returned by malloc()
[and family] is undefined behaviour.
根据您的问题,如果 malloc()
-ed 指针存储在 p
中,并且您执行 p++
并调用 free(p);
,那么 p
不再是 calloc
返回的指针>、malloc
或 realloc
函数.
As per your question, if the malloc()
-ed pointer is stored in p
, and you do p++
and call free(p);
, then there p
is not anymore a pointer returned by the calloc
, malloc
, or realloc
function.
根据第 7.20.3.2 章,c99
标准,第 2 段
As per Chapter 7.20.3.2, c99
standard, 2nd paragraph
free 函数导致 ptr 指向的空间被释放,即可供进一步分配.如果 ptr 是空指针,则不会发生任何操作.否则,如果参数与之前由 calloc、malloc 或 realloc 函数返回的指针不匹配,或者如果空间已通过调用 free 或 realloc 释放,则行为未定义.
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 中更改指针会释放多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!