Roberto Hernandez
Roberto Hernandez

Reputation: 33

SIGSEGV (Segmentation fault) C++ Pointers

Ok this is my code:

#include <iostream>
using namespace std;
class Nodo{
public:
    Nodo *siguiente,*anterior;
    string Nombre,Curso,Posicion;
    int carnet;
    Nodo(){
        siguiente=anterior=NULL;
        Nombre=Curso="";
        carnet=0;
    }
};
class ListaCircular{
public:
    Nodo *PrimerNodo,*UltimoNodo;    
    ListaCircular(){
        *PrimerNodo->siguiente=*UltimoNodo;
    }
};

int main(){
    ListaCircular *a=new ListaCircular();
    cout<<a->PrimerNodo->siguiente<<endl;
    return 0;
}    

When i try to run it it says "BUILD SUCCESSFUL" but "RUN FAILED", and when i debug it the SIGSEGV message appears, the line that seems to have an error is:

*PrimerNodo->siguiente=*UltimoNodo;

but if i run the program again without the lines:

ListaCircular *a=new ListaCircular();
cout<<a->PrimerNodo->siguiente<<endl;

then the program have a succesfull build and run.

How can I make that "cout" successfuly?

Upvotes: 1

Views: 779

Answers (4)

LihO
LihO

Reputation: 42083

In the constructor of this class:

class ListaCircular{
public:
    Nodo *PrimerNodo,*UltimoNodo;    
    ListaCircular(){
        *PrimerNodo->siguiente=*UltimoNodo;
    }
};

you are trying to dereference uninitialized pointer PrimerNodo, which produces undefined behavior. In your case it results to segmentation fault (which is actually good, because otherwise this kind of error might be hard to find).

One of the possible solutions is to create these objects of type Nodo within the constructor's body:

ListaCircular(){
    PrimerNodo = new Nodo();
    UltimoNodo = new Nodo();
    PrimerNodo->siguiente = UltimoNodo;
}

also note that this line:

cout << a->PrimerNodo->siguiente << endl;

will print the address of the memory that a->PrimerNodo->siguiente points to.

Upvotes: 3

Andersnk
Andersnk

Reputation: 867

I am still kinda of new to c++, so it might be that i am wrong, but shouldn't it be Primernodo->siguiente=Ultimonodo? in the ListaCircular class..

Also, what exactly are you trying to print? Are you trying to print the object, or what? you might want to add another '->' after "Siguiente, like " cout<<<a->PrimerNodo->siguiente->toString<< endl; or similar..

Upvotes: 1

QuentinUK
QuentinUK

Reputation: 3077

Define a new Nodo linking function:-

void Nodo::SetSiguiente(Nodo*sig){
    siguiente=sig;
    sig->anterior=this;
}

Fix the constructor:-

ListaCircular(){
    PrimerNodo = new Nodo;
    UltimoNodo = new Nodo;

    PrimerNodo->SetSiguiente(UltimoNodo);
    UltimoNodo->SetSiguiente(PrimerNodo);
}

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25695

it should be:

PrimerNodo->siguiente=UltimoNodo

But, UltimoNodo is not initialized, so dereferencing it could be illegal(UB).

Upvotes: 0

Related Questions