Exception error in Dynamic List C++

Asked

Viewed 300 times

0

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

Exception released: read access violation. j was 0xCCCCCC.

Can’t fix 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;
}
  • it is already being started: "Cell* j = source->Prox;" the error you are giving is when comparing the value of the object element that the pointer j points to with the value 'x' sent as parameter.

1 answer

0


The problem is here

Celula x; 

The value of x in the constructor is lost when exiting the function as 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;

}
  • It worked, you’ve had a few mistakes, but rest assured, thank you!

  • Good that it worked, good studies

  • new shouldn’t be used in normal code, ever, just when it’s really the last tool left. std::unique_ptr and other smart pointers should be the first tools to be considered.

Browser other questions tagged

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