简体   繁体   English

在先前 malloc 的指针上使用 realloc 会导致分段错误

[英]Using realloc on a previously malloc-ed pointer causes segmentation fault

i have problem with C, this code throw stack dump.我对 C 有问题,此代码抛出堆栈转储。 I don't have idea whats wrong.我不知道出了什么问题。

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;
}

In your code, you pass text as the first argument to realloc() and later, without checking for failure, you pass the same to free() .在您的代码中,您将text作为第一个参数传递给realloc() ,然后在不检查失败的情况下将其传递给free() That is what is causing the issue here.这就是导致这里出现问题的原因。

As per C11 , chapter §7.22.3.5根据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. realloc函数释放ptr指向的旧对象,并返回一个指向大小由 size 指定的新对象的指针。 [...] If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged. [...] 如果不能为新对象分配内存,则旧对象不会被释放并且其值不变。

So, if the realloc() is success, afterwards, calling所以,如果realloc()成功,之后,调用

free(text);

invokes undefined behavior .调用未定义的行为 You need not to bother about text anymore, remove the call to free() .您不再需要为text而烦恼,删除对free()的调用。

Related, for free() , §7.22.3.3相关, 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. [...] 否则,如果参数与内存管理函数先前返回的指针不匹配,或者如果空间已通过调用freerealloc释放,则行为未定义。

TL;DR First check for the success of realloc() , if success, don't touch text , if realloc() fails, then you need to call free(text); TL;DR首先检查realloc()是否成功,如果成功,请勿触摸text ,如果realloc()失败,则需要调用free(text);

You shouldn't free the pointer text because upon success realloc() deallocates the old pointer.您不应该释放指针text因为成功realloc()释放旧指针。

From C11 standard chapter 7.22.3.5 The realloc function:来自 C11 标准章节 7.22.3.5 realloc 函数:

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. realloc 函数释放 ptr 指向的旧对象,并返回一个指向大小由 size 指定的新对象的指针。 The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes.新对象的内容应与释放前的旧对象的内容相同,直到新旧大小中较小的一个。 Any bytes in the new object beyond the size of the old object have indeterminate values.新对象中超出旧对象大小的任何字节都具有不确定的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM