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

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -