Click to See Complete Forum and Search --> : how to debug segmentation fault


wise
01-19-2003, 01:57 PM
I compiled the following code successfully. However, I got segmentation fault when running on Linux. Could anybody tell me where my bug is? Thank you very much!!

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
char *string[]={"model", "speed", "size", "men",
"woman","version", "mark"};
FILE *in1, *in2, *in3, *out;
char line[BUFSIZ];
if (argc!=5)
{
fprintf(stderr, "Usage: test file1 file2 file3 out_file\n");
exit(1);
}

if ((in1=fopen(argv[1],"r"))==NULL)
{
perror(argv[1]);
exit(1);
}

if ((in2=fopen(argv[2],"r"))==NULL)
{
perror(argv[2]);
exit(1);
}

if ((in2=fopen(argv[3],"r"))==NULL)
{
perror(argv[3]);
exit(1);
}

if ((out=fopen(argv[4],"w+"))==NULL)
{
perror(argv[4]);
exit(1);
}

while (fgets(line, sizeof(line), in1)!=NULL)
{
if (strstr(line, string[0])!=NULL)
{
fputs(line,out);
}

if (strstr(line,string[1])!=NULL)
{
fputs(line,out);
}

if (strstr(line,string[2])!=NULL)
{
fputs(line,out);
}
}

while (fgets(line, sizeof(line), in2)!=NULL)
{
if (strstr(line, string[3])!=NULL)
{
fputs(line,out);
}

if (strstr(line,string[4])!=NULL)
{
fputs(line,out);
}
}


while (fgets(line, sizeof(line), in3)!=NULL)
{
if (strstr(line, string[5])!=NULL)
{
fputs(line,out);
}

if (strstr(line,string[6])!=NULL)
{
fputs(line,out);
}
}

fclose(in1);
fclose(in2);
fclose(in3);
fclose(out);
execl("/bin/cat", "cat", argv[4],0);
}
:)

truls
01-19-2003, 04:14 PM
You should add the -Wall option to your compiler.
Then you'll probably get something like:
warning C4700: local variable 'in3' used without having been initialized

bwkaz
01-19-2003, 06:58 PM
You could have added this to your other thread, where I first saw this problem... :rolleyes:

You never #define'd BUFSIZ anywhere -- what is it? It's obviously defined somewhere, but where?

Instead of using sizeof() still, just use BUFSIZ.

And put your code in [ code] ... [ /code] tags so that we can read it.

wise
01-19-2003, 07:12 PM
Thank you Bwkaz! I think you have already told me my error--I almost never used C. I also apologize for adding another thread.
Many thanks! Good luck to you!


Originally posted by bwkaz
You could have added this to your other thread, where I first saw this problem... :rolleyes:

You never #define'd BUFSIZ anywhere -- what is it? It's obviously defined somewhere, but where?

Instead of using sizeof() still, just use BUFSIZ.

And put your code in [ code] ... [ /code] tags so that we can read it.