1

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.

10ants
  • 255
  • 3
  • 10

2 Answers2

11

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;
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
3

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

Dipstick
  • 9,854
  • 2
  • 30
  • 30