带有realloc()的printf()崩溃了程序

时间:2014-04-03 14:26:15

标签: c memory-management printf memory-corruption

printf realloc 有一种奇怪的行为。了解堆腐败我做了一个简单的程序测试。

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();

}

当我从中删除printf时,程序会运行并显示:

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

当我把printf befor调用testFct时,程序会显示这行并崩溃。

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

如您所见,第二行显示重新分配后缓冲区的内容,根据MSDN,如果失败, ReAlloc 必须不更改缓冲区,但在我的情况下,它将缓冲区设置为< strong> null ,这就是 _msize 崩溃以及我的程序的原因 问题是:printf的行为是什么?我把它放在testFct之前发生了什么?

1 个答案:

答案 0 :(得分:5)

此:

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

导致未定义的行为。因此,对程序在该点之后的行为的任何分析都是毫无意义的。任何事情都可能发生。

另外,please don't cast the return value of malloc() in C