Could anyone tell me what is wrong with this code?
for(int i=0;i<4;i++)
{
long int a = strtol(strtok("1-2-3-4","-"),(char**)NULL,10);
cout << a <<endl
}
I'm running on Solaris Unix. It's giving me a segmentation fault.
The fault is in strtol()
.
The problems are legion.
I would expect that the core dump is because the string
"1-2-3-4"
is stored in read-only memory, so whenstrtok()
modifies it (to isolate the first token), the program crashes. You say the crash is instrtol()
; that would suggest that the return value fromstrtok()
is NULL.The first call to
strtok()
uses the string as an argument; the second call passes NULL in its place to indicate 'continue where you left off last time'. As written, if the string was modifiable, then you'd parse1
four times.This is closer to correct (though untested):
In general, you need to do error detection from
strtol()
; further, doing so is quite fraught. However, with the sample string, you would not have to worry about that.