2011-11-28 115 views
-1

我有下面这个程序,它从用户获取文件的数量,然后获取文件名,并将文件的内容读入优先级队列。当我执行该程序时,在输入第一个文件名后,会出现分段错误。从多个文件读取时出现分段错误

#include <cstdlib> 
#include <ctime> 
#include <functional> 
#include <iostream> 
#include <queue> 
#include <fstream> 
using namespace std; 

int main() { 
    char *filename; 
    int fnum; 

    cout<<"Number of files:"<<endl; 
    cin>>fnum; 

    int i; 
    priority_queue<int, vector<int>, greater<int> > pqi; 
    for(i = 0; i<fnum;i++){ 
     cout <<"Enter Filename:"<<endl; 
     cin>>filename; 
     ifstream inFile(filename); 
     long n; 
     while(!inFile.eof()){ 
      inFile >> n; 
      pqi.push(n); 
     } 
     inFile.close(); 
     inFile.clear(); 
    } 
    while(!pqi.empty()) { 
     cout << pqi.top() << ' '; 
     pqi.pop(); 
    } 
} 

无法找出原因。

+2

我可以建议编辑职位和修复你的代码的缩进? –

+3

你用调试器试过了吗? –

+0

如果这是一项家庭作业,您必须明确标记它'家庭作业'。 – Hossein

回答

3

问题出在您的char*定义。你只需定义一个指针,不要为它分配任何内存。您可以使用new关键字来分配内存吧:

char *filename = new char[256]; 
//... rest of your code ... 
//When you no longer need filename (usually at the end of the code) 
//you have to free the memory used by it manually: 
delete[] filename; 

在这个简单的情况下,你也可以使用一个静态数组:

char filename[256]; 
//No need to delete[] anything in this way. 

上述两种方式分配固定的内存量filename,这意味着如果用户在上述示例中输入的文件名长于256字节,我们会遇到缓冲区溢出。您可以使用string类型的自动执行存储管理,为您和易于使用:

#include <string> 
string filename; 
cin >> filename; 
+0

你可能意思是*缓冲区溢出*而不是在运行下。 – DarkDust

+0

谢谢。修复。 – Hossein

2

在你的代码有

char *filename; 

,以后你使用

cin>>filename; 

您只是分配给文件名没有空间,所以输入被写入到一些不确定的内存。要么将filename定义为char数组,要么使用std::string

相关问题