freinn
freinn

Reputation: 1079

reading string from file segmentation fault (core dumped)

class BPP
{
    unsigned            n;                  /* nº de instancias */
    vector<string>      nombre_instancia;   /* nombre de la instancia*/

In the constructor, I get a segmentation fault (core dumped) when:

file1.open(fich1);
    if (file1.is_open()){
        file1 >> (unsigned &) n;
        for (unsigned k = 0 ; k < n ; ++k){
            getline(file1, nombre_instancia[k]); #gives the segmentation fault

The 2 first lines in fich1 are:

10
 P_0

Upvotes: 0

Views: 664

Answers (3)

hmjd
hmjd

Reputation: 122001

You need to populate the vector with elements before accessing them via vector::operator[]. In the following code the vector is empty:

for (unsigned k = 0 ; k < n ; ++k){
    getline(file1, nombre_instancia[k]);

so the call to nombre_instancia[k] is out of bounds. You can use vector::resize() to create the elements:

if (file >> n) // Ensure 'n' correctly assigned.
{
    nombre_instancia.resize(n);
    for (unsigned k = 0 ; k < n ; ++k){
        getline(file1, nombre_instancia[k]);
}

An alternative is to use vector::push_back() without knowing up front what the number of elements will be.

Upvotes: 2

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11190

I think you need to reserve space in a vector if you want to use getline. By giving nombre_instancia[k], the program has an uninitialised vector. Use reserve, or push_back(null)

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168766

I guess that you have not resized nombre_instancia beyond its original size of 0. Try this instead:

  file1 >>  n;
  nombre_instancia.resize(n);     
    for (unsigned k = 0 ; k < n ; ++k){
        getline(file1, nombre_instancia[k]); #gives the segmentation fault

Upvotes: 2

Related Questions