简体   繁体   中英

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

i have problem with C, this code throw stack dump. 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() . That is what is causing the issue here.

As per C11 , chapter §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.

So, if the realloc() is success, afterwards, calling

free(text);

invokes undefined behavior . You need not to bother about text anymore, remove the call to free() .

Related, for 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 First check for the success of realloc() , if success, don't touch text , if realloc() fails, then you need to call free(text);

You shouldn't free the pointer text because upon success realloc() deallocates the old pointer.

From C11 standard chapter 7.22.3.5 The realloc function:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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