RE: [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: Ioannis V. <no...@ho...> - 2002-11-09 22:10:04
|
> -----Original Message-----
> From: dev...@li...=20
> [mailto:dev...@li...] On Behalf=20
> Of CRV=A7ADER /KY
> Sent: Saturday, November 09, 2002 3:20 PM
> To: dev...@li...
> Subject: [Dev-C++] sscanf() writes out of pointer and program=20
> doesn't segfault
>=20
>=20
> Using the following environment:
> Windows 98
> Dev-C++ 4.9.6.0 with included gcc (2.95.3-6)
>=20
> I compile the following program, *without any optimization*=20
> and with no=20
> additional compiler arguments:
>=20
#include <stdio.h>
>=20
> int main()
> {
> char instr[]=3D"600";
>=20
> short var1=3D800,
> var2=3D-1;
>=20
> printf("%d %d\n",var1,var2);
> sscanf(instr,"%i",&var2);
> printf("%d %d\n",var1,var2);
>=20
> getchar();
> return 0;
> }
>=20
>=20
> output:
> 800 -1
> 0 600
>=20
> expected output:
> 800 -1
> 800 600
>=20
> sscanf overwrites the preceding 2 bytes of RAM (occupied by=20
> 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.
>=20
> The fact is, ** program doesn't segfault **.
And? In official ANSI C standard terminology, the result is "undefined
behaviour". That is in your PC something else may be overwritten, a
crash to occur, the plane to crash (if this happens in a plane
navigation code for example).
>=20
> Also, the pointer should require an explicit (int *) cast to=20
> be accepted,=20
> otherwise a warning should occour ("Warning: implicit cast=20
> from "short *"=20
> to "int *"). It would be much useful, if possible.
No. sscanf() is a variadic function and a void * is passed. Depending ob
your argument, a corresponding pointer (int *) is assigned the void *
pointer.
>=20
> if var2 is declared as int instad of short, the problem is corrected.
> if optimizations are used, shorts are padded to int and the=20
> problem doesn't=20
> occour.
In general the resulting behaviour is undefined.
Ioannis Vranos
=20
* Programming pages: http://www.noicys.freeurl.com
* Alternative URL: http://run.to/noicys
|