c - Seg Fault while strcpy -
this relevant piece of code i'm working on. tokenize input stdin no issue , when go copy input, i'm getting segfault. however, no segfault "strcpy(s,input)". missing fundamental here? thank you
char *s = malloc(64 * sizeof(char)); char *token = malloc(64 * sizeof(char)); char *currstring = malloc(128 * sizeof(char)); currstring = null; fgets(input,100, stdin); strcpy(s, input); token = strtok(s,delim); while (token) { //condition checking strcpy(currstring,token); }
char *currstring = malloc(128 * sizeof(char)); currstring = null; you allocate memory, discard , set pointer null. rid of second line.
if trying set empty string (""), instead do:
currstring[0] = '\0'; // or strcpy(currstring, ""); this isn't necessary, though. don't need set string "" if you're going strcpy() later.
char *token = malloc(64 * sizeof(char)); you not need allocate memory token. strtok() cause token point somewhere within s, allocating memory token leak memory once token = strtok(s, delim);.
Comments
Post a Comment