如果我重新分配先前分配的内存区域的特定内存块,会发生什么?
#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
。
此外,在使用 [OP更新的代码片段]realloc()
时,请注意第二个参数。它应该是[总共]的新大小,不是与当前分配大小的差异。
同样,您必须使用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/