I'm trying to read an array from a file that has the arrays contents stored in a comma delimited list on a single very long line (about 346112 elements long).
I have a function that works sometimes, then other times it fails with a segmentation fault (core dump) error.
What is wrong with this code?
int* read(std::string fileName)
{
std::ifstream input(fileName.c_str());
std::string line;
getline(input, line);
std::string str = line;
std::vector<int> vect;
std::stringstream ss(str);
int i = 0;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
input.close();
return &vect[0];
}
Then I call it like this:
int* h_w1 = NULL;
h_w1 = (int*)malloc(sizeof(int) * 346112);
h_w1 = read("file.txt");
What the heck is wrong with this code?