views:

53

answers:

2

Hi:

I am trying to read from a file using fgets and sscanf. In my file, I have characters on each line of the while which I wish to put into a vector. So far, I have the following:

FILE *fp;
  fp = fopen(filename, "r");
  if(!fp)
  {
    fprintf(stderr, "Unable to open file %s\n", filename);
    return 0;
  }
  // Read file
  int line_count = 0;
  char buffer[1024];
  while(fgets(buffer, 1023, fp))
  {
    // Increment line counter
    line_count++;

    char *bufferp = buffer;

    ...

    while(*bufferp != '\n')
    {
      char *tmp;
      if(sscanf(bufferp, "%c", tmp) != 1)
      {
        fprintf(stderr, "Syntax error reading axiom on "
                "line %d in file %s\n", line_count, filename);
        return 0;
      }

      axiom.push_back(tmp);
      printf("put %s in axiom vector\n", axiom[axiom.size()-1]);

      // increment buffer pointer
      bufferp++;
    }
  }

my axiom vector is defined as vector<char *> axiom;. When I run my program, I get a seg fault. It happens when I do the sscanf. Any suggestions on what I'm doing wrong?

+2  A: 

tmp is a pointer and not an array so reading into it results in a buffer overrun.

for a start you should change the decleration of tmp to:

  char *tmp = malloc(SOME_MAXIMUM_SIZE * sizeof(char));

and then you should remember to free all of the pointers in axioms when you're done.

shoosh
+2  A: 

A safer approach is to use std::string and std::vector<std::string>.

The string type handles memory allocation for your text. See also getline and std::string::c_str().

Thomas Matthews
if you're going to take the step of using a std::string (and I wholeheartedly recommend you do), you may also want to switch to the C++ I/O classes for your file I/O (namely, fstream).
rmeador