Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!zaphod.mps.ohio-state.edu!rpi!masscomp!ocpt!tsdiag!moria!dcm From: dcm@moria.UUCP (David C. Miller) Newsgroups: comp.lang.c Subject: Re: Okay, here's a toughie for you... (maybe) Message-ID: <386@moria.UUCP> Date: 6 Dec 90 23:17:10 GMT References: <2784@ux.acs.umn.edu> Organization: The Black Chasm Lines: 62 In article <2784@ux.acs.umn.edu> edh@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