I have two helper functions for splitting strings in decimal format, i.e. "23.00", "2.30"
Consider this:
char price[4] = "2.20"; unsigned getDollars(char *price) { return atoi(strtok(price, ".")); } unsigned getCents(char *price) { strtok(price, "."); return atoi(strtok(NULL, ".")); }
Now, when I run below, I get a segmentation error:
printf("%u\n", getDollars(string)); printf("%u\n", getCents(string));
However, when I run them separately without following another, they work fine. What am I missing here? Should I do some strtok reset ??
My decision:
Thanks to the knowledge about strtok obtained from the answer I selected below, I changed the implementation of helper functions to first copy the passed in line, protecting the original line and preventing this problem:
#define MAX_PRICE_LEN 5 unsigned getDollars(char *price) { char copy[MAX_PRICE_LEN]; char tok[MAX_PRICE_LEN]; strcpy(copy, price); strcpy(tok, strtok(copy, ".")); if(tok == NULL) return 0; else return atoi(tok); } unsigned getCents(char *price) { char copy[MAX_PRICE_LEN]; char tok[MAX_PRICE_LEN]; strcpy(copy, price); strtok(copy, "."); strcpy(tok, strtok(NULL, ".")); if(tok == NULL) return 0; else return atoi(tok); }
source share