c - Segmentation fault after exit function -
this question has answer here:
parse line function handler:
char **parse_line(char *input) { char **tokens; char *token; char *seps = " \n"; token = strtok(input, seps); int = 0; while (token != null) { tokens[i] = token; i++; token = strtok(null, seps); } tokens[i] = null; return tokens; }
pipe function handler:
void pipes(char *input) { const char ch = '|'; printf("%s", input); char *c; if (strchr(input, ch) == null) { printf("no | found\n"); return; } printf("%s\n", input); char *p = strtok(input, "|"); int = 0; char *array0; char *array1; while (p != null) { if (i == 0) array0 = p; else array1 = p; i++; printf("p: %s\n", p); p = strtok( null, "|" ); } printf("opening\n"); parse_line(array1); }
main
int main(int argc, const char *argv[]) { while (1) { printf("> "); //read line char input[100]; fgets(input, sizeof(input), stdin); pipes(input); } ...
gdb output:
(gdb) cat scores | grep villanova undefined catch command: "scores | grep villanova". try "help catch". (gdb) run starting program: ******* > cat scores | grep villanova cat scores | grep villanova cat scores | grep villanova while while opening grep villanova program received signal sigsegv, segmentation fault. 0x00007fffffffddf2 in ?? () (gdb) x/s 0x00007fffffffddf2 0x7fffffffddf2: "villanova" (gdb) p $_siginfo._sifields._sigfault.si_addr $1 = (void *) 0x7fffffffddf2 (gdb) q
when stepping through gdb seg faults after reaches end of pipes
function. have idea why/ how can find out why , fix it.
i'm trying better @ debugging has stumped me , i'd appreciate can :)
the function parse_line
not allocate array tokens
point to. code has undefined behavior.
here simple corrected version:
char **parse_line(char *input) { size_t = 0; char **tokens = malloc(sizeof(*tokens)); char *token; const char *seps = " \n"; if (tokens == null) return null; token = strtok(input, seps); while (token != null) { char **newp = realloc(tokens, (i + 2) * sizeof(*newp)); if (newp == null) { free(tokens); return null; } tokens = newp; tokens[i++] = token; token = strtok(null, seps); } tokens[i] = null; return tokens; }
Comments
Post a Comment