1

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Deren
  • 85
  • 1
  • 7

2 Answers2

1

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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.

machine_1
  • 4,266
  • 2
  • 21
  • 42