Exception error in C ++ dynamic list

0

I'm creating a threaded list in C ++ and in condition if (j ->n == x) , in method wasVisited that should check if an element has already been inserted in the list, the following message appears when I compile:

  

Exception thrown: Read access violation.   j was 0xCCCCCC.

I can not solve it, can anyone help me? I'm using visualStudio as IDE.

#include "stdafx.h"
#include <iostream>
using namespace std;

class Celula{

public:
    int n;
    Celula* prox;

    Celula() {

        n = -1;
        prox = NULL;

    }//fim Construtor

    Celula(int x) {

        n = x;
        prox = NULL;

    }//fim construotor
};
class Lista {

public:
    Celula* origem;
    Celula* fim;

    Lista() {

        Celula x;
        origem = &x;
        fim = &x;

    }//fim construtor

    void inserir(int x) {

        Celula c(x);


        fim->prox = fim = &c;

    }//fim inserir

    bool wasVisited(int x) {

        bool res = false;
        Celula* j = origem->prox;

        do {

            if (j ->n == x) {

                res = true;

            }//fim if

            else {

                j = j->prox;


            }//fim else

        } while (res == false && j != NULL);//fim do.while

        return res;

    }//fim wasVisited


};

int main()
{
    Lista teste;

    teste.inserir(2);
    teste.wasVisited(2);
    teste.wasVisited(1);
    cin.get();

    return 0;
}
    
asked by anonymous 07.05.2018 / 00:07

1 answer

0

The problem is here

Celula x; 

The value of x in the constructor, is lost when leaving the function because it is a local variable. With this origem and fim become uninitialized values generating access to 0xCCCCCC. to solve this just change the construction:

Lista() {

   Celula *x = new Celula();
   origem = x;
   fim = x;

}
    
07.05.2018 / 00:58