realloc()问题:旧块的释放,旧大小的新大小,以及传递静态数组基址

Jug*_*gni 3 c memory-management realloc dynamic-memory-allocation

虽然读到realloc()我已经偶然发现了一些我需要澄清而不是忽视的疑问.你的答案非常受欢迎.为了清楚起见,我把它们放在一个编号列表中.请不要介意这个问题的长度.

1)在使用时realloc(),如果内存块及其内容被移动到一个新位置,那么orignal地址是否会被解除分配,好像我们在其上调用了free()?我已经从中读过以下cplusplusreference内容了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.会不会是UB这里也一样,我读free()的描述free() "If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior."

Dan*_*her 9

1)使用时realloc(),如果内存块及其内容被移动到新位置,那么原始地址是否会被取消分配,就像我们调用free()它一样?

是的,如果realloc()返回指向其他位置的指针,则旧位置为freed.

free如果realloc无法获得足够大的内存块并返回,则不是d NULL.

2)这是提出问题的另一条线:"如果新的大小更大,新分配的部分的值是不确定的.".嗯,这是我想知道的

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

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

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

填充垃圾,根本没有填充 - 内存块的内容是不确定的,除了从旧块复制的部分.你不应该关心那些东西,把它们放在那里然后再读它.

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

是的,如果您将参数(除外NULL)传递realloc给之前未调用的参数malloc,calloc或者realloc(之后没有free),则行为未定义.

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