简体   繁体   中英

Segmentation fault in push_back for a 2d vector

I'm learning c++ and I have a problem with a segmentation fault. In my project I want to read from a File into a 2d Vector of char. The Vector is std::vector<std::vector<char>> gamearea;

void Structure::readFile(const std::string filename) 
{ 
    std::ifstream file(filename.c_str()); 
    if (!file.is_open()) 
    { 
       std::cerr << "Error opening file: " << filename << std::endl;    
       exit(1); 
    } 
    std::string line; 
    int i = 0; 
    while (true) 
    { 
       std::getline(file, line); 
       if (file.eof()) 
       { 
          break; 
       } 
       for (size_t j = 0; j< line.length(); j++) 
       { 
           gamearea[i].push_back(line[j]); 
       } 
       i++; 
    } 
}

This is my read file function and the debugger (I use gdb) says by push_back is a segmentation fault.

Can someone help me? I can't find the problem.

You need to first push back into the first vector a std::vector<char> because by default the gamearea vector is empty, so when accessing gamearea[i] you end up accessing out of bounds (since gamearea has 0 elements inside it)

void Structure::readFile(const std::string filename) 
{ 
std::ifstream file(filename.c_str()); 
if (!file.is_open())  {
 std::cerr << "Error opening file: " << filename << std::endl; exit(1);
} 
std::string line; int i = 0; 
while (true) { 
    std::getline(file, line); 
    if (file.eof()) { break; } 

    // NOTICE HERE 
    // We add a new vector to the empty vector 
    std::vector<char> curArea;
    gamearea.push_back(curArea);


    for (size_t j = 0; j< line.length(); j++) {
       gamearea[i].push_back(line[j]); 
    } 
    i++;
  } 
}

Here is an example of properly reading in and updating your vector, given that it is empty:

void Structure::readFile(const std::string filename) 
{ 
   std::ifstream file(filename.c_str()); 
   if (!file.is_open())  {
       std::cerr << "Error opening file: " << filename << std::endl; 
   return;

   std::string line; 
   while (std::getline(file, line)) 
       gamearea.push_back(std::vector<char>(line.begin(), line.end()));
}

Live Example

Note we don't need to test for eof() . Also, all we need to do is call push_back an entire string of data using the two argument std::vector constructor that takes two iterators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM