Question

I have a strange behavior of printf with realloc. Understanding Heap Corruption I do a simple program test.

void testFct(){

char *buffer;
buffer = (char *)malloc( 8 );       //Allocate 8 bytes

strcpy(buffer,""abcdefghijklm");    //Generate memory overwrite

fprintf(stdout,"\nOrginal buffer = %s\t",buffer);
fprintf(stdout,"%d bytes\n",_msize(buffer) );

buffer = (char *)realloc(buffer,512);   //Reallocate more bytes

fprintf(stdout,"Buffer after reallocation = %s\t",buffer);
fprintf(stdout,"%u bytes\n",_msize(buffer) );

free(buffer);           //Free the buffer

fprintf(stdout,"Buffer after freed = %s\t\t",buffer);
fprintf(stdout,"%u bytes\n\n",_msize(buffer) );
} 

void main(){

  printf("something\n");
  testFct();

}

Whent I remove printf from the main, the program run and shows:

Orginal buffer = abcdefghijklm  8 bytes
Buffer after reallocation = abcdefgh    512 bytes
Buffer after freed = 0→h                0 bytes

When I put printf befor calling testFct, the program shows this lines and crash.

Orginal buffer = abcdefghijklm  8 bytes
Buffer after reallocation = (null)

As you see, the second line show the content of buffer after rellocation, according to MSDN, ReAlloc must don't change the buffer if it fails, but in my case it set buffer to null, this is why _msize crash and also my program.
The question is: What is the behavior of printf? what happened when I have put it before testFct?

Was it helpful?

Solution

This:

strcpy(buffer, "abcdefghijklm");    //Generate memory overwrite

causes undefined behavior. Thus, any analysis of the program's behavior past that point is kind of pointless. Anything could happen.

Also, please don't cast the return value of malloc() in C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top