当我们通过 重新分配内存时realloc()
,之前的内容会被覆盖吗?我正在尝试制作一个程序,每次我们将数据输入到其中时都会重新分配内存。
请告诉我有关通过 realloc 分配内存的信息,例如它是否依赖于编译器?
不要担心旧的内容。
正确的使用方法realloc
是使用特定指针进行重新分配,测试该指针,如果一切正常,更改旧指针
int *oldpointer = malloc(100);
/* ... */
int *newpointer = realloc(oldpointer, 1000);
if (newpointer == NULL) {
/* problems!!!! */
/* tell the user to stop playing DOOM and retry */
/* or free(oldpointer) and abort, or whatever */
} else {
/* everything ok */
/* `newpointer` now points to a new memory block with the contents of oldpointer */
/* `oldpointer` points to an invalid address */
oldpointer = newpointer;
/* oldpointer points to the correct address */
/* the contents at oldpointer have been copied while realloc did its thing */
/* if the new size is smaller than the old size, some data was lost */
}
/* ... */
/* don't forget to `free(oldpointer);` at some time */
它在不覆盖现有内容的情况下增长已经分配的内存,或者(如果它无法增长)它在不同的位置分配新的更大的内存并将现有内容从以前的内存复制到新的内存中。
您应该像旧指针被覆盖一样进行编程,是的。旧内存不再分配,因此可以由程序的另一部分(或系统线程)重新分配,并在调用 realloc 后随时重写。
新内存将始终包含与旧内存中相同的数据(如果需要,它会为您复制),但仅限于旧块的大小,最后分配的任何额外空间都将未初始化。
如果你想要一个副本然后做一个新的 malloc 并使用 memcpy。
在实现方面,当您调用 realloc 来增加大小时,可能会发生以下情况之一:
由于您无法知道发生了什么,或者即使使用了与上面建议的完全不同的实现,您应该始终根据 realloc 的规范进行编码,即您不能再使用旧指针并且您必须使用新的。
很难说你在问什么,但如果你问是否可以在传递给的旧地址读取“旧内容” realloc
,答案是否定的。在某些情况下,您可能会在那里找到部分或全部旧内容,但除非realloc
返回您传递给它的相同指针,否则对旧指针的任何使用都是未定义行为。
如果您只是询问是否将旧内容保留在返回的新地址中realloc
,答案是肯定的(直到旧大小和新大小的最小值)。