[英]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");
我看到幾個問題。
不要使用while (!foeof(a))
。 請參見為什么“ while(!feof(file))”總是錯誤的? 。
您沒有為這些單詞分配足夠的內存。 結果,您最終會使用本不該使用的內存。 這導致未定義的行為。
采用:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.