0

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?

alk
  • 69,737
  • 10
  • 105
  • 255
Phiber
  • 1,041
  • 5
  • 17
  • 40
  • "*... ReAlloc must don't change the buffer if it fails ...*" it probably doesn't, but if `realloc()` fails it returns `NULL` and with this sets `buffer` to `NULL`. – alk Apr 03 '14 at 14:32

1 Answers1

5

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.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • Ok. undefined bahavior, so my program may be run may be crash. for your second suggestion "don't cast the retrun value of malloc() in C", please change one line in my code to see. I do `char *buffer= malloc( sizeof(char) * 8 );` but don't compile (VS2008) **cannot convert from void * to char * ** . Thank you. hide help 303 characters left Comments use mini-Markdown formatting: [link](http://example.com) _italic_ – Phiber Apr 03 '14 at 14:43
  • ^ I am sure you are using C++ compiler. Try changing to 'c' – Digital_Reality Apr 03 '14 at 14:47
  • @Phiber Note that I said "in C". In C++, which you seem to be compiling as for some reason, the rules are different. If you want to program in C, make sure your compiler knows this. – unwind Apr 03 '14 at 14:50
  • Yes, it seems to be clear for me now. Thank you unwind, Digital_Reality and alk for editing the code. – Phiber Apr 03 '14 at 14:53