10ants
10ants

Reputation: 265

Standard C function atof returns segmentation faults when using with strtok

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

Answers (2)

Dipstick
Dipstick

Reputation: 10129

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

Upvotes: 3

Klas Lindb&#228;ck
Klas Lindb&#228;ck

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

Related Questions