0

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?

thebenman
  • 1,621
  • 14
  • 35
  • since the memory was already malloced the pointer is still valid. realloc() just performs a reallocation of previously malloced memory or if the pointer provided is NULL, it will do a malloc() instead. so in your example the memory area had been allocated. by removing the realloc() it was not reallocated or resized but the original pointer was still valid. – Richard Chambers Sep 26 '14 at 17:52
  • 1
    It does not work fine, you are corrupting the heap. And no, you are *not* guaranteed to get smacked on the finger knuckles doing this, your program will keel over when you least expect it. Long after the damage was done, making the bug as hard to possible to find. A lesson you'll remember. – Hans Passant Sep 26 '14 at 17:53

1 Answers1

2

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415