从多个文件读取时出现分段错误

时间:2011-11-28 07:41:13

标签: c++

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

#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 个答案:

答案 0 :(得分: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;

答案 1 :(得分:2)

在您的代码中

char *filename;

以后再使用

cin>>filename;

您没有为文件名分配空间,因此输入被写入某些未定义的内存。将filename定义为char数组,或使用std::string

相关问题