I have this following program which gets the number of files from user, then the filename and reads the content of the file in to a priority queue. When I execute the program, after I enter the first filename it gives segmentation fault.
#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();
}
}
Not able to figure out why.
The problem is with your
char*definition. You just define a pointer and don’t allocate any memory to it. You have to allocate memory to it using thenewkeyword:In this simple case you can also use a static array:
Both of the above ways allocate a fixed amount of memory to
filename, which means if user enters a file name longer than 256 bytes in the above examples we encounter a buffer overflow. You can usestringtype which automatically does the memory management for you and is easy to use: