Pointer changes address when exiting function

5

When performing a dynamic allocation of a vector or matrix in C, the pointer referring to this allocation changes address when leaving the function, whereas before it was pointing to the initial address of the allocated area and soon after the end of the respective area it points to address 1. As shown below, the pointer is passed as a parameter by the function to perform further manipulation of the allocated data.

#include <stdio.h>
#include <stdlib.h>

void aloca(int *vetorInt, int tamanho);

int main (void) {
    int *vetor;

    aloca(vetor, 2);
    printf("END. NA MAIN: %d", vetor);
}

void aloca(int *vetorInt, int tamanho) {
    //Inicializa o ponteiro com NULL para nao ter problema
    vetorInt = NULL;
    //Aloca n espaços
    vetorInt = (int *) malloc(tamanho * sizeof(int));

    //Verifica se foi alocado e exibe o endereço para qual o ponteiro aponta
    if (vetorInt != NULL) {
        printf("*** VETOR ALOCADO.\nENDERECO NA FUNCAO: %d ***\n", vetorInt);
        getchar();
    } else {
        printf("*** NAO ALOCADO ***\n");
        getchar();
    }
}

When I run the code, I verify that the address has changed and in the end I lose access to this vector, and can not perform memory deallocation or data manipulation. Why does it happen? What is the solution?

    
asked by anonymous 09.11.2016 / 20:17

2 answers

6

This is a classic problem in C. What happens is that the vetorInt pointer is local to the scope of the aloca function (just as the integer tamanho is). You modify the value of it within the function, but it is lost when you exit it, because the vetorInt variable ceases to exist.

There are two ways to work around this:

  • Make the function return the allocated address, and make vetor receive it in main .

  • Change the parameter of the variable in the function to a pointer pointer: int **vetorInt . So it is necessary to pass the pointer address in main ( &vetor ). Within the function, it is also necessary to refer to the variable as *vetorInt . As you can see, this method is a bit more confusing, especially for beginners.

09.11.2016 / 20:32
4

Ideally, it is better to allocate to the place you are going to use, so it is easier to trace what you need to release, but if you want to do so, it is best to return the pointer and not pass as a parameter, which complicates the syntax. I took what was unnecessary.

#include <stdio.h>
#include <stdlib.h>

int *aloca(int *vetorInt, int tamanho) {
    vetorInt = malloc(tamanho * sizeof(int));
    if (vetorInt != NULL) {
        printf("*** VETOR ALOCADO.\nENDERECO NA FUNCAO: %d ***\n", vetorInt);
    } else {
        printf("*** NAO ALOCADO ***\n");
    }
    return vetorInt;
}

int main (void) {
    int *vetor = aloca(vetor, 2);
    printf("END. NA MAIN: %d", vetor);
}

See working on ideone and on CodingGrround .

    
09.11.2016 / 20:39