Reputation: 85
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;
}
Upvotes: 1
Views: 227
Reputation: 134356
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 byptr
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
orrealloc
, 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);
Upvotes: 1
Reputation: 4454
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.
Upvotes: 0