realloc(): invalid next size when reallocating to make space for strcat on char *

PUG picture PUG · Dec 8, 2011 · Viewed 63.1k times · Source

I am getting invalid memory error on following code:

printf(" %s\n","FINE 5");
printf("%s LENGTH IS: %d\n","FINE 6",strlen(": "));
buffer = (char *)realloc(buffer, strlen(buffer)* sizeof(char) + (strlen(": ")+1)* sizeof(char));
printf(" %s\n","FINE 7");
strcat(buffer, ": \0");

Output:

FINE 5
FINE 6 LENGTH IS: 2
* glibc detected * ./auto: realloc(): invalid next size: 0x08cd72e0 *** ======= Backtrace: ========= /lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x6dd591]

The point to note here is Fine 7 is never printed. and invalid next size error on every run is at the same location.

Found this relavent

Answer

David Heffernan picture David Heffernan · Dec 8, 2011

This error occurs because some other part of your code has corrupted the heap. We can't tell you what that error is without seeing the rest of the code.

The fact that FINE 7 is not printed tells you that realloc is failing. And that failure must be because buffer is invalid due to a heap corruption earlier in the execution.


Orthogonal to your actual problem, sizeof(char) is 1 by definition so it makes sense to remove it from the code.