[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: strange SIGSEV



Robert Millan <rmh@aybabtu.com> writes:

> Hi!
>
> The following code seems to produce SIGSEV only on amd64 platforms (both on
> GNU/Linux and on GNU/kFreeBSD).  Anyone has an idea what is the portability
> problem here?
>
> Perhaps that buf is deallocated inmediately after getfoo() returns?  I could
> switch to strdup()/free() but I'd like to figure out what's going on first.
>
> $ cat buffer.c
> #include <string.h>
> char *
> getfoo()
> {
>         static char buf[128];
>         strcpy (buf, "foo");
>         return buf;
> }
> $ cat test.c
> #include <stdio.h>
> #include <sys/param.h>
> #include <sys/stat.h>
>
> main ()
> {
>   printf ("%s\n", getfoo ());
                    ^^^^^^
Typical 32bit BUG. You forgot to prototype getfoo(), so it become
"int getfoo (void)" by default. "int" is 32 bit on amd64, but
pointer is 64 bit, so you are calling printf() with truncated
to 32bit pointer. Use -Wall to detect these errors:

$ gcc -c test.c -Wall         
test.c:6: warning: return type defaults to 'int'
test.c: In function 'main':
test.c:7: warning: implicit declaration of function 'getfoo'
test.c:7: warning: format '%s' expects type 'char *', but argument 2 has type 'int'
test.c:8: warning: control reaches end of non-void function
$ 



Reply to: