3

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

1)在使用realloc()时,如果内存块及其内容被移动到一个新位置,原始地址是否会像我们调用 free() 一样被释放cplusplusreference?我已经从about中阅读了以下内容realloc,但尽管它们接近建议在这种情况下原始内存块确实会被释放,但我需要您的确认。

->C90 (C++98)C99/C11 (C++11) Otherwise, if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.

->If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).

2) 这是引起问题的另一行:"If the new size is larger, the value of the newly allocated portion is indeterminate."。好吧,这就是我想知道的

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

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

3)最后,如果传递一个数组对象到描述为realloc(char*"Pointer to a memory block previously allocated with malloc, calloc or realloc.free()free() "If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior."

4

1 回答 1

9

1)在使用realloc()时,如果内存块及其内容被移动到一个新位置,原始地址是否会像我们调用free()它一样被释放?

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

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

2)这是另一个提出问题的行:“如果新大小更大,则新分配部分的值是不确定的。”好吧,这就是我想知道的

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

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

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

填满垃圾,根本没有填满——内存块的内容是不确定的,除了从旧块复制的部分。你不应该关心那里有什么,在阅读之前把你自己的东西放在那里。

3)最后,如果传递一个数组对象realloc()怎么办?我问是因为,虽然类型仍然是char*,但在源站点中提到,参数应该是“指向先前分配的内存块的指针malloccalloc或者realloc。它也会是 UB,正如我在free()的描述中读到的那样为了free()

是的,如果您将参数(除了NULL)传递给realloc不是从之前的调用中获得的malloccalloc或者realloc(此后没有被freed),则行为是未定义的。

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

于 2013-05-21T18:27:57.140 回答