scanf, linux and solaris
Martin Kalen
martin.kalen@todaysystems.com.au
Wed Jun 6 07:08:00 GMT 2001
You have no allocated memory for the storage of username, it is just a
pointer - and more so, an uninitialised pointer. (The results may
actually vary from run to run.)
Either:
char username[xx];
or:
username = (char *)malloc(xx * sizeof(char));
Another good thing to do is to always initialise your local pointers
to NULL (on the toplevel this is automatic), eg:
#include <stdlib.h>
char* username = NULL;
This will trigger errors like this every time you run the program (eg.
write to address 0x0). The program has a more deterministic behaviour
and that can help you while debugging.
If you compile with lint, ElectricFence (should be on your Linux box),
Purify (available for Solaris) or any other memory checker you can
catch bugs like this at runtime. Coverage depends on the tool - Purify
is really good but also expensive.
Regards,
Martin.
P.S. This is not really gcc specific.
----- Original Message -----
From: "david smith" <nextl@angelfire.com>
To: <gcc-help@gcc.gnu.org>
Sent: Wednesday, June 06, 2001 11:50 PM
Subject: scanf, linux and solaris
> Hi, I've been trying to scan in a string using scanf. The following
code works fine on Solaris but breaks on Linux(tested on two different
boxes) with a seg fault. Currently it breaks when the username is
longer than 10 chars, on a previous attempt before rebooting it would
break when the username was longer than 6 chars.
> Any help would be appreciated.
>
> #include <stdio.h>
>
> main(){
> char* username;
> printf("Username:");
> scanf("%s", &username);
> }
More information about the Gcc-help
mailing list