I was hoping someone could help me figure out why I am getting a segmentation fault on my code below. My user has inputted a line of text, which is passed to the parse function. The parse function should initialize a 2D array (I would ideally like to dynamically allocate the array, but for now I am making it an array of size [25][25]).
Starting at the beginning of input strtok() is called. If strtok() sees a pipe symbol, it should increase the count of pipes and go to the next row of the matrix. For example, if the user inputted foo bar | foo1 | foo2 bar1 foo2, the 2D array would look like:
array[][] = { foo, barr;
foo1;
foo2, bar1, foo2; }
Eventually I would like to pass this array to another function. However, If I actually input the above into my program, this is the result:
/home/ad/Documents> foo bar | foo1 | foo2 bar1 foo2
test1
Segmentation fault
ad@ad-laptop:~/Documents$
Thus, given where I put these debug statements, the problem is with saving the tokens? This is the first time I have worked with a 2D array so I am sure it is something wrong with my pointer logic. What can I do to fix this segmentation fault? Thanks for your time.
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int MAX_PATH_LENGTH = 1024; //Maximum path length to display.
int BUF_LENGTH = 1024; // Length of buffer to store user input
char * delims = "|"; // Delimiters for tokenizing user input.
const int PIPE_READ = 0;
const int PIPE_WRITE = 1;
void execute(char *args, int numPipes, int numArgs){
int i;
int j;
for(i = 0; i <= numArgs; i++){
for(j = 0; j < 25; j++){
printf("args[%d][%d]", i, j);
}
}
}
void parse(char *input) {
char argArray[25][25];
int numPipes = 0;
int i = 0;
int j = 0;
char *tokenPtr = NULL;
tokenPtr = strtok(input, delims);
while(tokenPtr != NULL) {
if(strcmp(tokenPtr, "|") == 0){ //is token a pipe?
numPipes++;
i++;
j = 0;
}
else {
argArray[i][j++] = *tokenPtr;
printf("test1\n");
tokenPtr = strtok(input, NULL);
printf("test2\n");
}
}
execute(*argArray, numPipes, i);
}
int main () {
char path[MAX_PATH_LENGTH];
char buf[BUF_LENGTH];
char* strArray[BUF_LENGTH];
while(1) {
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
fflush(stdout);
fgets(buf, BUF_LENGTH, stdin);
parse(buf);
bzero(strArray, sizeof(strArray)); // clears array
}
}
Only the first call to strtok should receive the input. Subsequent calls (while parsing the same string) should have NULL as their first argument.