简体   繁体   English

sprintf的错误用法?

[英]wrong usage of sprintf?

I have simple test program 我有简单的测试程序

#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);
};

Test run on Linux, gcc 4.3.4: 在Linux上测试运行,gcc 4.3.4:

user@server /tmp $ ./a.out 
cOut address= f9f41880 
cpOut address = f9f41880 
cOut address= f9f41880 
cpOut address = f9f41880 

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

bash-3.00$ ./a.out
cOut address= 8047488
cpOut address = 8047488
cOut address= 8047488
cpOut address = 8000a20

Could anyone please explain me why pointer cpOut is overwritten by calling sprintf function ? 任何人都可以解释为什么指针cpOut被调用sprintf函数覆盖?

Because the string "2048 \\n" doesn't fit in char cOut[4]; 因为字符串"2048 \\n"不适合char cOut[4]; , you're creating a buffer overflow. ,你正在创建一个缓冲区溢出。

You are writing 7 bytes ("2048 \\n" + NUL) into an array of size 4 on the stack. 您正在将7个字节(“2048 \\ n”+ NUL)写入堆栈中大小为4的数组中。 This will overwrite 3 bytes of whatever is below it on the stack, which in this case is cpOut . 这将覆盖堆栈下面的3个字节,在这种情况下是cpOut The new value of cpOut shows you this: the first byte is unchanged 0x08, then the next 3 are the last three bytes of the string you're writing: 00 (NUL), 0a ('\\n'), 20 (' '). cpOut的新值向您显示:第一个字节未更改0x08,然后接下来的3个是您正在写入的字符串的最后三个字节:00(NUL),0a('\\ n'),20('' )。

I think it's a case of buffer overflow. 我认为这是缓冲区溢出的情况。 Try making cOut larger, also replace sprintf with the safer snprintf: 尝试使cOut更大,也用更安全的snprintf替换sprintf:

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

should be changed to 应改为

snprintf(cOut,sizeof(cOut),"%d \n", number);

this line: 这一行:

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

writes 7 characters : "2048 \\n\\0", but there is space only for 4 of them. 写入7个字符:“2048 \\ n \\ 0”,但只有4个字符有空格。 The value 0x8000a20 has contains (in reverse order) : space, new line, and character 0. 值0x8000a20包含(以相反顺序):空格,换行符和字符0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM