Mentor for C self study wanted

cpghost cpghost at cordula.ws
Tue Oct 23 15:27:18 PDT 2007


On Tue, 23 Oct 2007 23:24:09 +0200
Harald Schmalzbauer <h.schmalzbauer at omnisec.de> wrote:

> #include <stdio.h>
> 
> 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Ät 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) == 4 on 32bit
platforms, and sizeof(int) == 8 on 64bit platforms; while typically
sizeof(short) == 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.

-- 
Cordula's Web. http://www.cordula.ws/


More information about the freebsd-questions mailing list