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