Segmentation fault, can you help me?
Im getting a segmentation fault when trying to display an element of type (int)
template <class T>
void Lista<T>::imprimir()
{
NodoL *ptr = new NodoL开发者_如何转开发;
ptr->sig = pri->sig;
cout << *ptr->sig->elem; //THIS DISPLAYS CORRECTLY
cout << *ptr->sig->sig->elem; //SEGMENTATION FAULT
}
Are you sure sig is not NULL ?
template <class T>
void Lista<T>::imprimir()
{
NodoL *ptr = new NodoL;
ptr->sig = pri->sig;
cout << *ptr->sig->elem; //THIS DISPLAYS CORRECTLY
if(ptr->sig == NULL || ptr->sig->sig == NULL)
return;
cout << *ptr->sig->sig->elem; //SEGMENTATION FAULT
}
It appears you have a linked list, where sig
points to the next element of the list. Your code allocates a new node and makes it point at the tail of the existing node in pri
. If your list was only two elements long to start with, then this code naturally crashes when you attempt to print the third element because there's no such thing. The first element is *ptr->elem
, and the second is *pri->sig->elem
.
Make sure that elem
is a pointer that can be dereferenced, and that it's not either pointing to some invalid location in memory, or that it's not NULL. It seems that you have some type of linked list, and you are attempting to access a list-node that is two nodes away from the current node pointed to by ptr
. Either that node may not exist, and therefore sig
is an invalid pointer, or the node member elem
is an invalid pointer. Either way, you should definitely check pointers before you attempt to dereference so many steps. In fact, this may best be done with something like a for loop such as:
NodoL* temp = ptr;
for (int i=0; i < NUMBER; i++)
{
if (temp->sig == NULL)
break;
temp = temp->sig;
}
cout << *temp->elem << endl;
That way you will either pass through a certain NUMBER
of pre-specified nodes in the list from where you're currently at, or you will terminate the for-loop early because you've reached the end of the list.
精彩评论