Search code examples
c++segmentation-faultstack-smash

Segmentation fault on a read function


I have got some serious problems with Stack Smash Protection and now I get a new error -Segmentation fault-. I think it is strongly related to the fact that linux has some special protections. Can anyone please explain me why do I get Segmentation fault on this particular case?

vector<const char*> Words;
void read(){
    FILE* a;
    char s[100];
    a = fopen("text.txt", "r");
    while (!feof(a))
    {
        fgets(s, 100, a);
        char *newAlloc = new char[strlen(s)];
        strcpy(newAlloc, s);
        Words.push_back(newAlloc);
    }
    fclose(a);
}

update: I tried all of the solutions and modified the code, but the problem is still there, so I tried to reduce the code to this:

#include<iostream>
#include<stdio.h>

int main()
{

 FILE* a;
 a=fopen("text.txt", "r");
 fclose(a);

 }

It still gives me that error at the line with fopen.(which is mandatory in the exercise I'm solving) - I'm using Ubuntu 15.10 and QT Creator along with GCC compiler.

update: Solved it. I guess the problem was because I didn't give the full path to fopen. I'm new with ubuntu. Apparently there are some things different.

 char * a = "/home/codrinz/text.txt";
 FILE * file = fopen(a, "r");

Solution

  • I see couple of problems.

    1. Don't use while (!foeof(a)). See Why is “while ( !feof (file) )” always wrong?.

    2. You are not allocating sufficient memory for the words. As a consequence, you end up using memory that you are not supposed to. This leads to undefined behavior.

    Use:

    while (fgets(s, 100, a))
    {
       char *newAlloc = new char[strlen(s) + 1];  // Add +1 for the terminating null character.
       strcpy(newAlloc, s);
       Words.push_back(newAlloc);
    }