Date: Wed, 24 Oct 2007 00:26:49 +0200 From: cpghost <cpghost@cordula.ws> To: Harald Schmalzbauer <h.schmalzbauer@omnisec.de> Cc: freebsd-questions@freebsd.org Subject: Re: Mentor for C self study wanted Message-ID: <20071024002649.6cc41512@epia-2.farid-hajji.net> In-Reply-To: <200710232324.09851.h.schmalzbauer@omnisec.de> References: <200710232044.53240.h.schmalzbauer@omnisec.de> <20071023220134.3abd635e@epia-2.farid-hajji.net> <20071023162454.93851854.wmoran@potentialtech.com> <200710232324.09851.h.schmalzbauer@omnisec.de>
next in thread | previous in thread | raw e-mail | index | archive | help
On Tue, 23 Oct 2007 23:24:09 +0200 Harald Schmalzbauer <h.schmalzbauer@omnisec.de> wrote: > #include <stdio.h> >=20 > void main() > { > short nnote; ^^^^^ > // Numerischen Notenwert einlesen > printf("Bitte numerischen Schulnotenwert eingeben: "); > scanf("%d",&nnote); ^^^^^ > I found that declaring nnote as int soleves my problem, but I > couldn=C4t understand why. > Another one was the result of default: nnote was -1077942208 instead > of 9 for example. There's a mismatch here: scanf("%d", ...) expects a pointer to int, while &nnote is a pointer to a short. Normally, an int occupies more bytes in memory than a short (typically sizeof(int) =3D=3D 4 on 32bit platforms, and sizeof(int) =3D=3D 8 on 64bit platforms; while typically sizeof(short) =3D=3D 2). So scanf(3) tries to store the result into 4 bytes, but you've provided a pointer to only 2 bytes of memory. Where will the other 2 bytes be stored by scanf? In your example, short nnote is an automatic variable: i.e. it's stored on the stack. So the other 2 bytes will be also saved on the stack, on a place that's not reserved for this. There could be anything there, like, say, a part of the return address for the function, or it could be on some page in memory that's read-only or non-allocated. In either case, the program behaviour is undefined, and this normally means it dumps core. So either replace "short nnote" with "int nnote", OR change "%d" to the appropriate format string identifier for short int "%hd" (look up "man scanf" for a list of those identifiers), both in scanf and printf calls. -cpghost. --=20 Cordula's Web. http://www.cordula.ws/
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20071024002649.6cc41512>