[Solved] realloc fails when printf is in code / weird chars


Your code exhibits undefined behaviour because you passed a non-static, uninitialised pointer to realloc whose contents were indeterminate.

From C11, Memory Management Functions:

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 ptr does not match a pointer earlier returned by a memory
management function, or if the space has been deallocated by a call to
the free or realloc function, the behavior is undefined.


Possible fixes:

  • Initialize it with 0 / NULL.
  • Declare it as static.ยน
  • Replace it with a call to malloc.

The realloc function returns a pointer to the new object (which may
have the same value as a pointer to the old object), or a null pointer
if the new object could not be allocated.

realloc returns NULL on failure, your code should check for it.

#include <errno.h>

char *line = 0;
errno = 0;

char *new = realloc (line, size);
if (!new) {
    perror ("realloc");
    /* realloc() failed to allocate memory, handle error accordingly. */
}

The above code snippet can be rewritten as:

#include <errno.h>

errno = 0;

char *new = malloc (size);
if (!new) {
    perror ("malloc");
    /* malloc() failed to allocate memory, handle error accordingly. */
}


Similarly, opendir returns a NULL pointer while lstat returns -1 to indicate an error. Check for them.


[1] โ€” Objects declared with static storage duration and are always initialised. In the absence of a definition, they are implicitly initialised to 0.

From the C standard C11 6.7.9/10:

“… If an object that has static or thread storage duration is not
initialized explicitly, then:

โ€” if it has pointer type, it is initialized to a null pointer;

โ€” if it has arithmetic type, it is initialized to (positive or
unsigned) zero;”

Though, it’s good practice to explicitly set it to 0.

solved realloc fails when printf is in code / weird chars