如果指针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()
.
指针传递到免费()
它不受返回的malloc()
[家庭]是< A HREF =https://en.wikipedia.org/wiki/Undefined_behavior>未定义行为。
Passing a pointer to free()
which is not returned by malloc()
[and family] is undefined behaviour.
根据你的问题,如果的malloc()
-ed指针存储在 P
,和你做点++
并调用免费(p);
,那么 p
是不再指向 按的的释放calloc
,的malloc $ C $返回C>或
的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
标准,第二段
As per Chapter 7.20.3.2, c99
standard, 2nd paragraph
的自由功能使空间指向由ptr被解除分配,即,用于进一步分配可用。若ptr为空指针,不会发生任何操作。否则,如果该参数不匹配的释放calloc,malloc或realloc函数返回前面的指针,或者如果空间已被释放呼叫释放或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屋!