So, I am getting a seg fault whenever I try to call strtok_r, however I am not completely sure why. I am getting this error within this block of code.
I know my error is coming from this section of code, because if I were to take out this while loop, and replace with simply just a printf(str); I get no errors and it prints correctly.
Below is my method containing strtok_r:
void parseCommand(char *str)
{
char *curr;
char *temp = str;
char **args=NULL;
int i = 0;
curr=strtok_r(temp, " ", &temp);
while(curr!=NULL){
args[i]=curr;
curr=strtok_r(NULL," ",&temp);
i++;
}
for(int j = 0;j<i-1;j++){
printf("%s", args[j]);
}
}
If my understanding of seg faults are correct, this is happening because I am trying to access some sort of memory that this process doesn't have permission to access, but I am unsure why. Anything helps!
EDIT: I have tried to experiment with this a little bit, and had assumed that there wasn't a null terminator at the end of my string, however when I added the line
strncat(cur,"\0",50);
to the inside of my while loop, just before I assign to args[i] the same result is yielded.
EDIT: updated strtok_r usage
char **args=NULL
...args[i]=curr;
. You never allocated any space for args. – Christian Gibbonsstrtok_r
incorrectly. Only the first call shall passtemp
. All following calls shall passNULL
– 4386427