Search code examples
cmallocrealloc

What does realloc do in this code snippet?


I was going through the relloc example in C here . I could not figure out exactly what realloc() was doing in this snippet, because even when I commented out the realloc statement the program ran just fine. I am attaching the Code here again so that it'll be easier to go through.

#include <stdio.h> 
#include <stdlib.h>

int main()
{
char *str;

/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s,  Address = %u\n", str, str);

/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s,  Address = %u\n", str, str);

free(str);

return(0);
}

As far as I understood malloc() initially allocated the string to be 15 bytes long, and then realloc() reassigned it to be 25 characters long. But how does it still work fine even though i remove the realloc() statement from the snippet? Am i missing something from this?


Solution

  • But how does it still work fine even though i remove the realloc() statement from the snippet?

    If you remove realloc(), maybe the code works fine but that is an accident. The code is still wrong, it has a buffer overrun, and the result is "undefined behavior" -- which means that it might work fine, it might crash, it might give the wrong answer, it might format your hard drive -- it might do anything.

    Fix your code.

    If you are using GCC 4.8 or newer, I suggest using the address sanitizer. Compile your code like this:

    gcc main.c -o main -fsanitize=address -Wall -Wextra
                       ^^^^^^^^^^^^^^^^^^
    

    This requires the address sanitizer library to be installed on your system. Alternatively, run your code in Valgrind's memcheck tool.

    valgrind ./main
    

    Both tools will show that your program is wrong.