读取功能的分段错误

Segmentation fault on a read function

我在使用 Stack Smash Protection 时遇到了一些严重的问题,现在我收到了一个新错误 - 分段错误 -。我认为这与 linux 具有一些特殊保护这一事实密切相关。谁能解释一下为什么我在这种特殊情况下会出现分段错误?

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);
}

更新:我尝试了所有的解决方案并修改了代码,但问题仍然存在,所以我尝试将代码简化为:

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

int main()
{

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

 }

它仍然在带有 fopen 的那一行给我这个错误。(这在我正在解决的练习中是强制性的)- 我正在使用 Ubuntu 15.10 和 QT Creator 以及 GCC 编译器。

更新:解决了。我想问题是因为我没有给出 fopen 的完整路径。我是 ubuntu 的新手。显然有一些不同。

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

我看到几个问题。

  1. 不要使用 while (!foeof(a))。见 Why is “while ( !feof (file) )” always wrong?.

  2. 您没有为单词分配足够的内存。结果,您最终使用了不应该使用的内存。这会导致未定义的行为。

使用:

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);
}