I was given the parseInput
function from a teacher. I am not able to get it to run without a segmentation fault and I hope you guys can help me.
I think it has to do with how I pass total_cmd_words
, but I'm not sure.
// Libraries
#include <stdio.h>
#include <string.h>
int parseInput(char *input, char* splitWords[]){
int wordInd = 0;
splitWords[0] = strtok(input, " "); // VSCODE says this line is causing the fault
while(splitWords[wordInd] != NULL){
splitWords[ wordInd] = strtok(NULL, " ");
}
return wordInd;
}
int main(){
char* total_cmd = "file1 > file2";
char* total_cmd_words[] = {};
parseInput(total_cmd, total_cmd_words);
}
gdb gives this output:
__GI___strtok_r (s=0x555555556006 "file1 > file2", delim=0x555555556004 " ",
save_ptr=0x7ffff7fb0ca8 <olds>) at strtok_r.c:72
72 strtok_r.c: No such file or directory.
Changing:
char* total_cmd_words[] = {};
to this:
char* total_cmd_words[100] = {};
Still results in a segmentation fault.
CodePudding user response:
There are two errors in your main
function.
First, your declaration of total_cmd_words
is wrong: as it stands, you're declaring an array of zero length – so there is no space to actually store the pointrs returned by the strtok
function in your parseInput
function. You need to specify a dimension for the array inside the []
– one that is large enough to hold the maximum number of values that your are likely to encounter.
Second, a call to strtok
modifies the string given as its first argument. However, your total_cmd
is a pointer to a non-mutable string literal. Instead, declare that as an array of char
and initialize it with a copy of the string literal.
Here's a possible working version of your main
:
int main()
{
char total_cmd[] = "file1 > file2";
char* total_cmd_words[10] = {0,};
int p = parseInput(total_cmd, total_cmd_words);
printf("%d\n", p);
}
CodePudding user response:
When you declared
char* total_cmd_words[] = {};
you didn't specify an array length. Therefore, it's length was determined by your initializer which was empty.
So, when you do
splitWords[0] = strtok(input, " ");
you're assigning to the first element of a 0-length array. That's undefined behavior and the most likely cause of your segmentation fault.
CodePudding user response:
Added sizes to total_cmd_words and total_cmd
// Libraries
#include <stdio.h>
#include <string.h>
int parseInput(char *input, char* splitWords[]){
int wordInd = 0;
splitWords[0] = strtok(input, " ");
while(splitWords[wordInd] != NULL){
splitWords[ wordInd] = strtok(NULL, " ");
}
return wordInd;
}
int main(){
char total_cmd[100] = "file1 > file2";
char* total_cmd_words[10] = {0,};
int p = parseInput(total_cmd, total_cmd_words);
printf("%d \n", p);
}
Thank you everyone for you help!