user2999242
user2999242

Reputation: 1

Segmentation fault (core dumped)

I have an assignment in "Operating Systems" class. Everything is fine with the rest of my code, i compile it with "gcc -o test test.c -Werror -Wall -pedantic -Wextra -Wfatal-errors ", no errors or whatsoever. But when i run it, i get a Segmentation fault(core dumped). I put some printf at various stages of the program to see at which point I get an error (inserted !!problem occurs here). I am out of options on this one. Any help is appreciated!

Part of the program:

void inputToken(char *cmdInput)
{
int i;
int quit = 0;
char *token;
char *argList[] = {"\0", "\0", "\0", "\0", "\0", "\0", "\0"};
char *argv[] = {"&", "%"};

token = strtok(cmdInput, " ");
i = 0;

while(token != NULL && i<7)
{
argList[i] = token;
token = strtok(NULL, " ");
i++; 
}

for(i=7; i>0; i++)
{
if(strcmp(argList[i], argv[0]) == 1) !!PROBLEM OCCURS HERE
    {
    <<SOME CODE>>
         }
 }
}


/*READING USER COMMAND*/
void usrInput()
{
int c;
int i=0;
char cmd[101];

while((c = getchar()) != EOF)
{
 if(c == '\n')
   break;
else if(i<100){
 cmd[i]=c;
 i++;
     }
  }

Thank you in advance!

Upvotes: 0

Views: 738

Answers (2)

Yabada
Yabada

Reputation: 1758

First, in the program parameters, argv[0] is your program name, so it will never be equal to "\0" :

./prog 12 lol -> argv[0] = "prog" | argv[1] = "12" | argv[2] = "lol"

Then to avoid seg fault, you must known that an array is 0 based. So your argList array have a size of 7, from 0 to 6 (var i must be DEcremented):

for (i = 6; i >= 0; i--)
  if(strcmp(argList[i], argv[0]) == 1) !! NO PROBLEM OCCURS HERE
    {
    <<SOME CODE>>
    }
  }
}

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

An array in C is 0 indexed. argList[i] is out of bounds if i is 7 and this is what happens on the first iteration of:

for(i=7; i>0; i++)
{
  if(strcmp(argList[i], argv[0]) == 1) !!PROBLEM OCCURS HERE
    {
    <<SOME CODE>>
         }
  }
}

Upvotes: 1

Related Questions