Home > other >  Why am i getting seg. fault?
Why am i getting seg. fault?

Time:09-07

I'm starting with pointers, and I can't see the reason why I'm getting a segfault with this code. I guess I'm accessing the array the wrong way, so how should I access it?

const int MAXIMO_LIBROS_INICIAL = 20;

typedef struct {
    string titulo;
    char genero;
    int puntaje;
} libro_t;

int main(){
    libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL];
    int tope_libros = 0;

    libros[tope_libros]->titulo = "hola";

    return 0;
}

CodePudding user response:

You are creating an array of pointers that don't point anywhere. You are getting a segfault from trying to access invalid memory. You need to create the individual objects that the pointers will point at, eg:

const int MAXIMO_LIBROS_INICIAL = 20;

struct libro_t {
    string titulo;
    char genero;
    int puntaje;
};

int main(){
    libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL];
    for (int i = 0; i < MAXIMO_LIBROS_INICIAL;   i) {
        libros[i] = new libro_t;
    }

    int tope_libros = 0;

    libros[tope_libros]->titulo = "hola";
    ...

    for (int i = 0; i < MAXIMO_LIBROS_INICIAL;   i) {
        delete libros[i];
    }
    delete[] libros;

    return 0;
}

Though, you really have 1 level of indirection too many, and should drop one level of *, eg:

const int MAXIMO_LIBROS_INICIAL = 20;

struct libro_t {
    string titulo;
    char genero;
    int puntaje;
};

int main(){
    libro_t* libros = new libro_t[MAXIMO_LIBROS_INICIAL];
    int tope_libros = 0;

    libros[tope_libros].titulo = "hola";
    ...

    delete[] libro_t;
    return 0;
}

That being said, consider using std::vector or std::array instead, let them manage the memory for you, eg:

#include <vector> // or: <array>

const int MAXIMO_LIBROS_INICIAL = 20;

struct libro_t {
    string titulo;
    char genero;
    int puntaje;
};

int main(){
    std::vector<libro_t> libros(MAXIMO_LIBROS_INICIAL);
    // or: std::array<libro_t, MAXIMO_LIBROS_INICIAL> libros;

    int tope_libros = 0;

    libros[tope_libros].titulo = "hola";
    ...

    return 0;
}
  • Related