1

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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().

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.