This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: scanf, linux and solaris




On Wed, 6 Jun 2001, david smith wrote:

> 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);
> }
>
>
>
> Get 250 color business cards for FREE!
> http://businesscards.lycos.com/vp/fastpath/
>
Thank god if such code breaks as often as possible, for you can find this
bug quite fast with core files and debuggers. Besides such code may break
any time (or it may not) if you overwrite some allocated space, which will
be harder to find !

Try out this scanf call, but be aware that you have no chance to test the
user writes more into your memory than you want him to ! You have no
chance to get real control over your stupid users if you use scanf. You
have to read char by char or definite blocks of chars to be sure.

You can allocate memory by a call to malloc (which allocates on heap) or
you can use prereserved space by defining an array of chars:

char	username[10];
which allocates 10 bytes for username.

As an exercise see what happens when you write:
struct user_name
{
	char	user[11];
	char	name[11];
} uname;

memset( &uname, ' ', sizeof(uname) );
uname.user[10] = 0;
uname.name[10] = 0;
printf( "\n user=\"%s\", name=\"%s\"\n", uname.user, uname.name );
printf( "username:" );
scanf("%s", uname.user);
printf( "\n user=\"%s\", name=\"%s\"\n", uname.user, uname.name );

if you insert more than 10 characters!

The function memset can be found in string.h . This example is a bit more
complex but somewhat astonishing when learning memory management in C!

CU INGO


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]