Memory junk when pointing a pointer

Asked

Viewed 85 times

0

In an attempt to implement an adjacent matrix graph, I created the function to create a new "matrix" in which the contents of the graph would be copied to it by adding the new positions. However, when calling this function and printing the new graph, the output contains several memory junk. Where is the error?

class GrafosMatriz{
    public:
     int *grafo;
     int tam;

GrafosMatriz(int tam){
    this->tam = tam;
    grafo = new int[tam*tam];
        for(int i = 0 ; i < tam*tam; i++)
                grafo[i] = 0;

}
void criarVertice(){
    tam++;
    int *aux = new int[tam*tam]; //matriz aux declarada com n+1
        for(int i = 0 ; i < tam*tam; i++){
            aux[i] = 0;
        }

        for(int i = 0,  j = 0; i < tam*tam - tam; i++){ //Passar pela matriz nova de tamanho n+1, sem passar na ultima linha
            if(i%tam != 0){  // pular a ultima coluna da matriz
                j++;
               aux[i] = grafo[j];
            }
        }

        grafo = aux;
        delete aux;

}
  • When you create a variable without giving a value to it will always have garbage, because it will have a number aletorio. Just when you create the matrix and don’t enter any value it will occur. That’s what you’re talking about?

  • But "aux" has been filled with zeros, it has value. But when pointing "graph" to "aux", memory junk appears

  • with the tam incremented, you are accessing non-existent indexes in the grafo.

  • But they are existing in aux, and graph starts to point to aux, no? I’m wrong?

  • You are making graph point to aux and not copying, and then Cvoce faz del aux. That memset after allocating space for graph is unnecessary, the new function already initializes with 0.

No answers

Browser other questions tagged

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