[Dev-C++] sscanf() writes out of pointer and program doesn't segfault
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: /KY <cru...@in...> - 2002-11-09 13:21:28
|
Using the following environment:
Windows 98
Dev-C++ 4.9.6.0 with included gcc (2.95.3-6)
I compile the following program, *without any optimization* and with no=20
additional compiler arguments:
int main()
{
char instr[]=3D"600";
short var1=3D800,
var2=3D-1;
printf("%d %d\n",var1,var2);
sscanf(instr,"%i",&var2);
printf("%d %d\n",var1,var2);
getchar();
return 0;
}
output:
800 -1
0 600
expected output:
800 -1
800 600
sscanf overwrites the preceding 2 bytes of RAM (occupied by var1), since it=
=20
thinks that var2 is an int (4 bytes) while actually it is a short (2=20
bytes), effectively writing out of the given pointer.
The fact is, ** program doesn't segfault **.
Also, the pointer should require an explicit (int *) cast to be accepted,=20
otherwise a warning should occour ("Warning: implicit cast from "short *"=20
to "int *"). It would be much useful, if possible.
if var2 is declared as int instad of short, the problem is corrected.
if optimizations are used, shorts are padded to int and the problem doesn't=
=20
occour.
Guido Imperiale
cru...@in...
-------------------------------
CRV=A7ADER/KY
KnowledgE is PoweR
|