I have a string that I get by getline()
(more precisely I use a loop and getline
to read a file line by line)
Let's say the line is 12|34|
Then I use strtok() to cut it down by substr = strtok(line, "|");
and store them into a string array with a loop, part[index] = substr;
So the part[0] here should be "12" and part[0] is "34" I would like to use strtol, but I have checked that it can't be used on string literal, then I try following code.
char *temp = strdup(part[1]);
char **ptr;
long ret = strtol(temp, ptr, 10);
printf("%x\n", ret);
and when I read the second line, it causes segmentation fault. By how can I really use strtol
to convert the string into integer
the issue is that
ptr
isn't initialised. So whenstrtol
tries to write at the addressptr
, it crashes (or undefined behaviour).You have to pass the valid address of a pointer to store the last unprocessed char, like:
&ptr
is valid and points to the auto variable storage location toptr