Program Crashing at random

Asked

Viewed 44 times

0

I am working with C++ Lists and while doing the following list implementation code:

#include <iostream>

using namespace std;

class NO{

    int idade;
    string nome;
    NO *no;

    public:

        void setDados(int, string);
        int getidade();
        string getnome();
        void setNext(NO*);
        NO* getNext();  
        ~NO(){};        

};

class Lista{

    NO *inicio;

    int quant_el;

    public:     

        Lista(){

            quant_el = 0;
            inicio->setNext(NULL);          

        }

        void inserir(int, string);  
        void pesquisar(NO); 
        void remover(int);
        void listar();      

};


void NO :: setDados(int idade, string nome)
{
    this->idade = idade;
    this->nome = nome;
}

int NO :: getidade()
{
    return idade;
}

string NO :: getnome()
{
    return nome;
}

void NO :: setNext(NO *no)
{
    this->no = no;
}

NO* NO :: getNext()
{
    return no;
}

void Lista :: inserir(int idade, string nome)
{
    NO *aux;
    aux = inicio;

    NO *novo = new NO();

    novo->setDados(idade, nome);
    novo->setNext(NULL);

    if(quant_el == 0)
    {
        inicio->setNext(novo);
        quant_el++;
    }
    else
    {
        while( (aux->getNext()) != NULL )
        {
            aux = aux->getNext();
        }
        aux->setNext(novo);
        quant_el++;
    }
    cout << "Foi inserido '" << idade << " " << nome << "'" << endl;
}

void Lista :: pesquisar(NO obj)
{
    NO *aux;

    int i;
    int cont = 1;
    int cont1 = 0;

    aux = inicio;

    if(quant_el == 0)
    {
        cout << "Não há nenhum dado na sua Lista." << endl;
    }
    else
    {
        for(i = 0; i < quant_el; i++)
        {
            cont++;
            if(((aux->getNext())->getidade() == obj.getidade()) && ((aux->getNext()->getnome() == obj.getnome())))
            {
                cont1++;
                break;
            }
            aux = aux->getNext();
        }
        if(cont1 == 0)
        {
            cout << "O dado não foi encontrado." << endl;
        }
        else
        {
            cout << "Dado encontrado na posição " << cont - 1 << endl;
        }
    }
}

void Lista :: remover(int pos)
{
    int i;

    NO *aux, *aux1;
    aux = inicio;
    aux1 = aux->getNext();

    if(pos > quant_el)
    {
        if(quant_el == 0)
        {
            cout << "Sua lista está vazia, não há elementos para remover." << endl;
        }
        else
        {
            cout << "Posição inválida, sua lista possui menos elementos." << endl;
        }
    }
    else
    {
        for(i = 0; i < pos - 1; i++)
        {
            aux = aux1;
            aux1 = aux1->getNext();
        }
        aux->setNext(aux1->getNext());

        quant_el --;
        cout << "Dado " << i + 1  << " removido: " << endl << aux1->getidade() << " " << aux1->getnome() << endl << endl;
        delete aux1;
    }
}


void Lista :: listar()
{

    int i;

    NO *aux;

    aux = inicio;

    if(quant_el == 0)
    {
        cout << "Sua lista está vazia, não há elementos para mostrar." << endl;
    }
    else
    {
        for(i = 1; i <= quant_el; i++)
        {
            cout << i << " Dado:" << endl;
            cout << aux->getNext()->getnome() << endl << aux->getNext()->getidade() << endl << endl;

            aux = aux->getNext();
        }
    }
}


int main()
{
    setlocale(LC_ALL, "");

    Lista lista1;

    NO loiola, rangel, humb;

    loiola.setDados(18, "Loiola");
    rangel.setDados(29, "Eustáquio");
    humb.setDados(23, "Humberto");

    lista1.inserir(18, "Filipe");
    lista1.inserir(29, "Eustáquio");
    lista1.inserir(10000, "Raul Seixas");
    lista1.inserir(18, "Leticia");
    lista1.inserir(18, "Mayra");
    //lista1.inserir(23, "Humberto"); Se um nó a mais for inserido, o programa crasha


    lista1.pesquisar(loiola);   
    lista1.pesquisar(rangel);
    //lista1.pesquisar(loiola); Se um nó a mais for pesquisado, o programa crasha.

    lista1.remover(2);

    lista1.remover(3);

    lista1.remover(1);

    lista1.listar();

    lista1.listar(
    );

    return 0;
}

You can also access at https://codeshare.io/5DvbWO

The program started crashing out of nowhere by searching for more than 2 nodes or inserting more than 5. There are no compilation errors, the program simply crashes.

Would anyone know what the problem is?

From now on, thank you.

  • 1

    The ideal would be to put the code in the publication

  • What you did to try to fix the problem?

  • I tested your code (but initialized the "start" variable (start = new NO; // in the constructor) or else it would stop right at the beginning of the execution) and it worked by uncommenting the two lines you showed. When "crash" occurs which message shows?

1 answer

0

You need to hit a lot of things in your code:

  • In the list builder you are doing setNext about the No inicio that was not even instantiated:

    Lista() {
        quant_el = 0;
        inicio->setNext(NULL); //<-- aqui
    }
    

    Once you have just built the list it will be better not to build the start node until a node is added. So you just need to remove the instruction I marked.

  • Still referring to initial cases, in his method of inserir when it does not yet have elements and according to the solution I gave in the previous point may not use pointer inicio.

    if(quant_el == 0)
    {
        inicio->setNext(novo); //<---aqui
        quant_el++;
    }
    

    For when quant_el is 0 inicio not yet allocated. Just switch to:

    if(quant_el == 0)
    {
        inicio = novo;
        quant_el++;
    }
    

    So the first knot will be the inicio. The increment itself quant_el++; so much is being done in the if as in the else And so you can simplify by taking both of them out and then following this block.

  • In the search you are using the front node to make the comparisons once it calls with ->getNext():

    if(((aux->getNext())->getidade() == obj.getidade()) && ((aux->getNext()->getnome() == obj.getnome())))
    //---------^------------------------------------------------------^
    

    This makes the last test the front knot, which is NULL and crash with Segmentation fault. Simplify in parentheses and test with the node itself:

    if(aux->getidade() == obj.getidade() && aux->getnome() == obj.getnome()) {
    
  • In the method listar fell into the same problem of displaying the front element instead of the current element:

    cout << aux->getNext()->getnome() << endl << aux->getNext()->getidade() << endl << endl;
    //-------------^-------------------------------------^
    

    Which easily fixes by removing only the ->getNext().

    I also call attention to the built-up that begins in 1 and ends equal to the value of quant_el:

    for(i = 1; i <= quant_el; i++)
    //------^-----^
    

    Usually begins in 0 and runs while it’s smaller, something very common for arrays. The way it did has tended to cause problems, but as in this particular case this value is only used to show on screen ends up having no impact.

View the code with all these changes and working on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.