Oscar
Oscar

Reputation: 243

ANSI C sscanf giving segfault

I am reading a "," delimited CSV file and trying to convert the token to a integer with sscanf and getting segfault error.

Here is my code:

#define MAX_LINE_SIZE 1024
#define DELIMITER ','

void load_data(char * coinsfile)
{

   char temp_line[MAX_LINE_SIZE];
   char * token;
   int number_coin;

   while (fgets(temp_line, MAX_LINE_SIZE, coins_file) != NULL) {
      token = strtok (temp_line, DELIMITER);
      while(token != NULL) {
         token = strtok (NULL, DELIMITER);
         sscanf(token, "%d", &number_coin);
      }
   }
}

testing CSV file:

5,10
10,5
20,8
50,2
100,20
200,8

Upvotes: 0

Views: 202

Answers (2)

Crowman
Crowman

Reputation: 25926

#define DELIMITER ','

Should be:

#define DELIMITER ","

and:

strtok(temp_line, &DELIMITER);

should be:

strtok(temp_line, DELIMITER);

The second argument to strtok() should be a NUL terminated string, you're probably getting your segfault because it's not, although passing NULL to sscanf() per the other answer is also not good. Reversing the order of these two lines:

token = strtok (NULL, DELIMITER);
sscanf(token, "%d", &number_coin);

may have been what you intended, otherwise you're not reading in the first number on each line. token would always be non-NULL at the start of the loop, this way.

Upvotes: 0

Constantin
Constantin

Reputation: 8961

This reads from stdin instead of an file, but it works without SEGFAULT. Notice the additional check for token != NULL before sscanf().

Example Input:

12;22;

Code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX_LINE_SIZE 1024
#define DELIMITER ";"

int main(int argc, char** argv){
  char temp_line[MAX_LINE_SIZE+1];
  char * token;
  int number_coin;
  while (fgets(temp_line, MAX_LINE_SIZE, stdin) != NULL) {
    token = strtok (temp_line, DELIMITER);
    while(token != NULL) {
      token = strtok (NULL, DELIMITER);
      if(token != NULL)
        sscanf(token, "%d", &number_coin);
    }
  }
  return 0;
}

Upvotes: 3

Related Questions