c - 重新分配与其偏移量不同的已分配内存块

标签 c memory-management realloc

如果我重新分配先前分配的内存区域的特定内存块,会发生什么?


#include <stdlib.h>

int main(void)
{
    char *area = malloc(15 + 1);

    strcpy(area, "Stack / Overflow");
    realloc(area + 5, strlen(area) + 5);

    return EXIT_SUCCESS;
}

在此示例中,area 字符串是否会扩展 5 个字节?

Idx: 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21
Chr: S  t  a  c  k  \0 \0 \0 \0 \0     /       O   v   e   r   f   l   o   w   \0

最佳答案

未定义的行为。 realloc() 需要由 malloc() 或系列返回的指针或 NULL

根据c99,第 7.20.3.4 章,第 3 段,对于 void *realloc(void *ptr, size_t size); [强调我的]

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.


除此之外,在您的代码中

char *area = malloc(15 + 1);
strcpy(area, "Stack / Overflow");

您没有为终止 null 分配空间。结果可能是毁灭性的。请添加空间来存储终止符\0

此外,在使用 realloc() 时,请注意第二个参数。它应该是[总共]的大小,不是当前分配大小的差异。 [OP更新的代码片段]

同样,您必须使用realloc()的返回值来访问新分配的内存。旧指针可能不再有效。请阅读man page了解详情。

所以对于你来说,代码应该是这样的

#include <stdlib.h>

int main(void)
{
    char *area = malloc(17);   //space for terminating null
    char * area_next = NULL;


    strcpy(area, "Stack / Overflow");   //cpy 16 chars, with null
    area_next = realloc(area, 23);                  // oldsize + 5

    return EXIT_SUCCESS;
}

关于c - 重新分配与其偏移量不同的已分配内存块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27921581/

相关文章:

c - 为什么函数必须返回 char * 而不是 char 数组?

vsnprintf 能否返回大于 1 的负值?

c - C 语言的基本结构帮助

c - 此代码段中双指针和三指针的意义

c - 使用 realloc 缩小数组,丢失第一个元素

c - 信号 : SIGABRT (Aborted) @ realloc

c++ - TraMineR R 包中的 C_cstringrefseqdistance 和 C_cstringdistance 函数

c++ - 在释放内存之前总是重新分配内存是否安全 - C++

objective-c - 在连续的内存块中分配objective-c对象

Java:即使代码正确,递归也会导致堆栈溢出错误