0

我在使用 Stack Smash Protection 时遇到了一些严重的问题,现在我收到了一个新错误 -Segmentation fault-。我认为这与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");
4

1 回答 1

3

我看到了几个问题。

  1. 不要使用while (!foeof(a)). 请参阅为什么“while (!feof (file))”总是错误的?.

  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);
}
于 2016-04-05T20:15:30.527 回答