Reputation: 265
I have problem with using atof and strtok.
#include<stdio.h> // printf
#include<stdlib.h> // atof
#include<string.h> // strtok
int main()
{
char buf[256]="123.0 223.2 2314.2";
char* tp;
printf("buf : %s\n", buf);
tp = strtok(buf," ");
printf("tp : %g ", atof(tp));
while (tp!=NULL) {
tp = strtok(NULL," ");
printf("%g ", atof(tp));
}
return 0;
}
I can compile above code and it returns no errors or warning messages. but when I execute "a.out", then it returns segmentation fault like below.
78746 Segmentation fault: 11 ./a.out
I don't know what is problem. as I see, above code doesn't compound syntactic error.
Upvotes: 1
Views: 2206
Reputation: 10129
You are passing tp to atof without checking that it is non-null.
Upvotes: 3
Reputation: 33273
When tp
becomes null you do atof
on it!
Rewrite your loop like this:
int main()
{
char buf[256]="123.0 223.2 2314.2";
char* tp;
printf("buf : %s\n", buf);
tp = strtok(buf," ");
printf("tp :");
while (tp!=NULL) {
printf("%g ", atof(tp));
tp = strtok(NULL," ");
}
return 0;
}
Upvotes: 10