Misuse of sprintf?

I have a 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);
};

Testing on Linux, gcc 4.3.4:

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

Testing on Solaris 10, Sun C ++ 5.10:

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

Can someone explain to me why the cpOut pointer is overwritten by a call to the sprintf function?

+3
source share
4 answers

Since the string is "2048 \n"not suitable for char cOut[4];, you create a buffer overflow.

+6
source

7 ( "2048\n" + NUL) 4 . 3 , , cpOut. cpOut : 0x08, 3 , : 00 (NUL), 0a ('\n'), 20 ( '').

+4

I think this is a case of buffer overflow. Try making cOut bigger, and also replace sprintf with safer snprintf:

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

should be changed to

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

this line:

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

writes 7 characters: "2048 \ n \ 0", but there is room only for 4 of them. The value 0x8000a20 contains (in reverse order): space, a new line, and the character 0.

+1
source

Source: https://habr.com/ru/post/1775676/


All Articles