Standard C function atof returns segmentation faults when using with strtok

2.1k views Asked by At

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.

2

There are 2 answers

0
Klas Lindbäck On BEST ANSWER

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;
}
0
Dipstick On

You are passing tp to atof without checking that it is non-null.