Okay, here's a toughie for you... (maybe)
David C. Miller
dcm at moria.UUCP
Fri Dec 7 10:17:10 AEST 1990
In article <2784 at ux.acs.umn.edu> edh at ux.acs.umn.edu (Eric D. Hendrickson) writes:
>The below program does not work. It seg faults in the last for loop. Can
>someone see what is wrong here? I suspect I have made a mistake using the
>pointers somewhere, but after much trial and error, little progress has
>been made. Perhaps you can see what it is...
>
>thanks,
> Eric
>(btw -- if this is not a good question for comp.lang.c, please let me know)
>char **
>extract(grep)
>char grep[];
>{
...
> char found[MAXPRINTERS][BUFSIZ]; /* holds found entries */
...
> return((char **)found);
...
>}
...
>int
>chores(grep)
>char *grep;
>{
> static char **gots;
> char **extract();
>
> gots = (char **)extract(grep);
> for( ; **gots != (char)'\0'; printf("%s\n", gots++)) ;
>}
You have 2 major problems:
1. In extract() you are returning a pointer to an automatic
variable. Once you return from extract() found[] no
longer exists and references to its address yeild
undefined results.
2. Also, found[] is not initialized. Automatic variables
are not automatically initialized to zeros. chores()
expects to find zeros in the first unused slot in found[].
Fortunately, the solution is quite easy. Move found[] outside the
extract() function and make it static. Moving it out of the function
eliminates both problems, making it static makes it invisible to
functions outside of this file. However, if you intend to call
extract() more than once, you'll have to make the following change
to extract():
*** Before
--- After
*** 48,49
fclose(fp);
return((char **)found);
--- 48,50
fclose(fp);
+ found[j][0] = '\0';
return((char **)found);
Laters,
David
More information about the Comp.lang.c
mailing list