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
So the part here should be "12" and part 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); 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 when
strtol tries to write at the address
ptr, it crashes (or undefined behaviour).
You have to pass the valid address of a pointer to store the last unprocessed char, like:
char *ptr; long ret = strtol(temp, &ptr, 10);
&ptr is valid and points to the auto variable storage location to