Segmentation fault?

Michael J. Chinni, SMCAR-CCS-W mchinni at pica.army.mil
Tue Feb 26 03:23:45 AEST 1991


From: Aasmodeus <widyono at eniac.seas.upenn.edu>
Date: 25 Feb 91 00:12:44 GMT
> int getline(FILE *fp, char *line); /* decl. should it be line[]? */
> main(int argc, char *argv[])
> {
>   char line[BUFSIZ];		/* line of input */
>   while (getline(fp, line) > 0) {
>     printf("%s\n", *line);	
>     if ((sscanf(line, "%1s", &label) == 1) &&
> 	.
> 	.
> 	.
> }  
> int getline(FILE *fp, char *line)
> {
>   if (fgets(line, BUFSIZ, fp) == NULL)
>     return 0;
>   else
>     return strlen(line);
> }
> 
> now, everything seems to work fine until the call to getline...
> in fact, even the call works (I used GDB to step thru).  However,
> when it returns, the next command fails.
> 
> In the case of the above, the error comes in _doprnt.
> 
> If I take out the printf right after the while, the error is found
>   in main().
> The error?  Segmentation fault!
> What is going on!?  This is on a Unix system.  SunOS Release 4.1.

I see a couple of problems with this code.

First the printf should use "line" not "*line". Reason is "*line" will use the
contents of "line" as an address to look at to get the string to print. This
will probably result in an address that is outside of the storage space of your
program.

Second in your sscanf unless label is declared as a character string (char.
array) the sscanf will not work right. Sscanf expects, if format is %1s,
storage space for a minimum of 2 characters (char. read plus '\0'). The error
when you removed the printf is probably in the sscanf. The reason this might
cause an error is that you are telling it to read a 1 character string and
store it (assuming label is declared properly for a character string and not as
just a single character (i.e. not "char label")) at the address of the address
of label, not the address of label.  This will probably be an address outside
of the storage space of your program.  The fix for this is: 1) with the format
"%1s", the storage location should either be "label" (assuming label is declared
as a char. array with a minimum of two elements (i.e. char label[2] minimum);
or 2) if label is declared as "char label" the format should be "%c".

P.S. it would have been more helpfull if the declaration for "label" had been
included as well.

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
			    Michael J. Chinni
	 US Army Armament Research, Development, and Engineering Center
                       Picatinny Arsenal, New Jersey  
     ARPA: mchinni at pica.army.mil     UUCP: ...!uunet!pica.army.mil!mchinni
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



More information about the Comp.unix.wizards mailing list