Date: Wed, 24 Oct 2007 14:15:53 +0300 From: Giorgos Keramidas <keramida@ceid.upatras.gr> To: Harald Schmalzbauer <h.schmalzbauer@omnisec.de> Cc: freebsd-questions@freebsd.org Subject: Re: Mentor for C self study wanted Message-ID: <20071024111552.GA2765@kobe.laptop> 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 2007-10-23 23:24, Harald Schmalzbauer <h.schmalzbauer@omnisec.de> wrote:
> Thanks all,
> here was my example, just for completeness, I found mentors for my
> needs.
> #include <stdio.h>
>
> void main()
> {
> short nnote;
>
> // Numerischen Notenwert einlesen
> printf("Bitte numerischen Schulnotenwert eingeben: ");
> scanf("%d",&nnote);
You are passing "%d" to scanf() so it expects to find enough 'storage'
in its pointer argument for an 'int'. If 'short' happens to have a
smaller size (as is commonly the case), scanf() will overwrite random
memory locations after 'nnote'. On systems where 'nnote' is stored in
the stack (because it's an automatic/local variable of main()), you are
risking stack corruption (and a SEGFAULT *may* happen).
It's also a very good idea to check the return code of scanf():
int nnote;
if (scanf("%d", &nnote) != 1) {
error;
}
> switch (nnote)
> {
> case 1: printf("Die Note %d entspricht sehr gut.",nnote);
> break;
> case 2: printf("Die Note %d entspricht gut.",nnote);
> break;
> case 3: printf("Die Note %d entspricht befriedigend.",nnote);
> break;
> case 4: printf("Die Note %d entspricht ausreichend.",nnote);
> break;
> case 5: printf("Die Note %d entspricht mangelhaft.",nnote);
> break;
> case 6: printf("Die Note %d entspricht ungen?gend.",nnote);
> break;
> default: printf("%d ist keine zul?ssige Schulnote!");
There's no `int' argument to the printf() call of the default clause.
This will either cause printf() to print random garbage, or try to
access memory regions which are unmapped and SEGFAULT.
> P.S.:
> I found that declaring nnote as int soleves my problem, but I couldn?t
> understand why.
> Another one was the result of default: nnote was -1077942208 instead
> of 9 for example.
It was never assigned to 9 :)
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20071024111552.GA2765>
