gpt4 book ai didi

c - 在先前 malloc ed 指针上使用 realloc 会导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:31 25 4
gpt4 key购买 nike

我对 C 有问题,这段代码抛出堆栈转储。我不知道怎么了。

char *text;
text = (char *) malloc(sizeof (char));
int size = 1;
char c = 'a';
char *new;
while (1) {
c = getchar();
putchar(c);
if (c == 10) {
text[size - 1] = '\0';
break;
}
text[size - 1] = c;
size++;
new = (char *) realloc(text, size * sizeof (*new));
free(text);
text = new;
}

最佳答案

在您的代码中,您将 text 作为第一个参数传递给 realloc(),随后,在不检查是否失败的情况下,将相同的传递给 free( )。这就是导致这里出现问题的原因。

根据 C11,章节 §7.22.3.5

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. [...] If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

所以,如果 realloc() 成功,之后调用

free(text);

调用 undefined behavior .您无需再为 text 操心,删除对 free() 的调用。

相关,对于free(),§7.22.3.3

[...] Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

TL;DR 首先检查realloc()是否成功,如果成功,不要碰text,如果 realloc() 失败,则需要调用 free(text);

关于c - 在先前 malloc ed 指针上使用 realloc 会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37059598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com