sprintf的错误用法?

jan*_*ano 3 c c++ printf

我有简单的测试程序

#include <stdio.h>
int main( int argc , char* argv[] )
{
  unsigned int number=2048;

  char* cpOut;
  char cOut[4]; 
  cpOut=(char*)&cOut[0];
  printf("cOut address= %x \n",&cOut[0]);
  printf("cpOut address = %x \n",cpOut);

  sprintf(&cOut[0],"%d \n", number);

  printf("cOut address= %x \n",&cOut[0]);
  printf("cpOut address = %x \n",cpOut);
};
Run Code Online (Sandbox Code Playgroud)

在Linux上测试运行,gcc 4.3.4:

user@server /tmp $ ./a.out 
cOut address= f9f41880 
cpOut address = f9f41880 
cOut address= f9f41880 
cpOut address = f9f41880 
Run Code Online (Sandbox Code Playgroud)

在Solaris 10,Sun C++ 5.10上运行测试:

bash-3.00$ ./a.out
cOut address= 8047488
cpOut address = 8047488
cOut address= 8047488
cpOut address = 8000a20
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么指针cpOut被调用sprintf函数覆盖?

unw*_*ind 6

因为字符串"2048 \n"不适合char cOut[4];,所以您正在创建缓冲区溢出.