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:
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:
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 ?
Because the string "2048 \n"
doesn't fit in 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. This will overwrite 3 bytes of whatever is below it on the stack, which in this case is 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 (' ').
I think it's a case of buffer overflow. Try making cOut larger, also replace sprintf with the safer snprintf:
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. The value 0x8000a20 has contains (in reverse order) : space, new line, and character 0.
精彩评论