c - realloc() 发出 : deallocation of old block, 新大小大于旧大小,并传递静态数组基地址

标签 c dynamic-memory-allocation realloc memory-management

在阅读有关 realloc() 的文章时,我偶然发现了一些我需要澄清而不是忽略的疑问。非常需要您的答案。为了清楚起见,我将它们放在一个编号列表中。请不要介意这个问题的长度。

1) 在使用 realloc() 时,如果内存块及其内容被移动到新位置,原始地址是否被释放 就好像我们在上面调用了 free() 一样?我从 cplusplusreference 中读到了关于 realloc 的以下内容,但尽管它们接近于暗示原始内存块做在这种情况下被释放,但我需要你的确认。

->C90 (C++98)C99/C11 (C++11) 否则,如果 size 为零,先前在 ptr 分配的内存将被释放,就像调用 free 一样,并返回一个空指针。

->如果函数未能分配请求的内存块,则返回一个空指针,并且参数 ptr 指向的内存块不会被释放(它仍然是 有效,且内容不变)。

2) 这里还有一行提出问题:“如果新的大小更大,新分配的部分的值是不确定的。”。嗯,这里是我想知道的

i) 是否允许写入新分配的部分?

ii) 新分配的部分是否使用垃圾值填充?

3) 最后,如果将一个数组对象 传递给realloc() 会怎么样?我问是因为,虽然类型仍然是char*,在源站中提到,参数应该是"指向一个之前用malloc, calloc or realloc分配的内存块的指针。会不会是 UB 也在这里,正如我在 free() 的描述中读到的那样,对于 free() “如果 ptr 不指向一个 block 使用上述函数分配的内存,会导致未定义的行为。”

最佳答案

1) While using realloc(),if the memory block with its contents are moved to a new location,does the orignal address gets deallocated as if we called free() on it?

是的,如果 realloc() 返回指向不同位置的指针,则旧位置是空闲d。

如果realloc 未能获得足够大的内存块并返回NULL,则不是freed。

2) Here's another line that raise questions: "If the new size is larger, the value of the newly allocated portion is indeterminate.".Well,here is what I want to know

i) Is it allowed to write into that newly allocated portion?

是的,当然。这就是重新分配更大内存块的全部意义所在。

ii) Is the newly allocated portion filled using garbage values?

充满垃圾,根本没有被填满——内存块的内容是不确定的,除了从旧 block 复制的部分。您不应该关心什么位,在读取之前将您自己的内容放在那里。

3) And finally,What if pass an array object to realloc()? I ask because,though type will still be char*,it is mentioned in the source site that, the argument should be "Pointer to a memory block previously allocated with malloc, calloc or realloc. Will it be UB here too,as I read in free()'s description that for free()

是的,如果您将参数(NULL 除外)传递给 realloc,但该参数不是从先前调用 malloc 获得的,callocrealloc(从那以后就没有 freed),行为未定义。

可以合法传递给 realloc 的指针与可以传递给 free 的指针完全相同。

关于c - realloc() 发出 : deallocation of old block, 新大小大于旧大小,并传递静态数组基地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16676795/

相关文章:

c - 生产者/消费者解决方案

c - 回收动态内存是什么意思?

c - 为什么 free() 不释放所有分配的内存位置?

c - 在 C 中通过引用传递二维动态分配的双数组

c - realloc() C语言改变int数组中的值

c - 为什么当我输入错误的数据类型时我的 C 程序没有崩溃

C中简洁和非干扰性的错误处理

c - 为什么 realloc 因临时指针而失败

c - 程序输出错误

c、从头开始shrink分配的空间