乐闻世界logo
搜索文章和话题

Does realloc overwrite old contents?

1个答案

1

In C, the realloc function is used to reallocate the size of a memory block. This is typically used when the initially allocated memory size no longer suffices for current requirements. Regarding whether realloc overwrites old content, the answer is: typically not, but it depends on the specifics of the memory reallocation.

The realloc function attempts to adjust the size within the original memory block location. If the new size can be adjusted in place (i.e., without moving the memory block to another location), the old content is not overwritten, and the original data is preserved. However, if the new size is too large to be adjusted in place, realloc finds a new sufficiently large memory block, copies the original data to the new location, and frees the old memory block.

A key point to note is that during data copying, only the data of the original memory block size is copied to the new location. If the new memory block is larger than the old one, the initial content of the extra portion is undefined, typically uninitialized.

For example, suppose you initially allocate an array of 10 integers, and later you need more space, such as 20 integers. If there is sufficient free memory adjacent to the original memory region, realloc may extend the memory in place. But if there is insufficient space, it allocates a new location to store the array of 20 integers, copies the original 10 integers' data to the new location, and preserves the original 10 integers' data. During this process, the content of the additional 10 integers is undefined, and you need to initialize it yourself.

In summary, realloc ensures data continuity and integrity, although additional data initialization steps may be required in some cases. When using realloc, always check its return value to ensure successful memory allocation and handle potential memory copying to ensure data correctness.

2024年7月22日 17:44 回复

你的答案