Return local function variables

Asked

Viewed 601 times

3

I have two methods:

// Apenas define um vetor de 4 posições e retorna ele
int *verticesFromFace(int v1, int v2, int v3, int v4) {
  int vertices[4] = {v1, v2, v3, v4};
  return &(vertices);
}

// pega um cubo e uma face dele, retorna um vetor de vertices daquela face
Vertice *getPointsFromFace(Cube c, Face f) {
  Vertice points[4];
  int i;
  for (i = 0; i < FACE_VERTICES; i++)
    points[i] = c.vertices[f.vertices[i] - 1];

  return &(points);
}

Example of use:

// pega uma face do cubo, armazena nela o vetor de vértices (usando aquele método) e também as cores daquela face (3 últimos parâmetros)
createFace(c.faces[0], verticesFromFace(1, 2, 3, 4), 1, 0, 0);


// Um vetor de vertices, quando chamo o metodo com o cubo e uma face do cubo
Vertice *points = getPointsFromFace(c, c.faces[i]);

GCC returns the error:

Warning: Function Returns address of local variable [-Wreturn-local-addr] Return &(points[0]);

Although it is a Warning, the code does not work because the local variable is not returned. How can I fix this?

P.S. &() in return was an attempt I made when I saw a post on Stack Overflow English

1 answer

4


You can’t do that. The array is allocated in the stack, when the function ends it can no longer be accessed.

The worst is that in C you can even in some circumstances that you have no control over and that can be tragic because most programmers think that if they test and work it’s right. Every language has these things, but C has so much more. C allows you to do a lot of things wrong and look right. Luckily this case went wrong before it was too late.

Understand What are and where are the "stack" and "heap"?.

To keep the value "alive" when leaving the function you need to allocate the object in the heap. This is done with malloc(). And then you have to release him with free(). Very experienced programmer slips and lets memory leak. Or you can try to release what has already been released, which can be tragic. Beginner programmer usually doesn’t even worry about it because it "works" without it.

All this code is wrong. It would be something like this:

int *verticesFromFace(int v1, int v2, int v3, int v4) {
    int *vertices = malloc(4 * sizeof(int));
    //inicaliza os elementos aqui
    return vertices;
}

I put in the Github for future reference.

Asymmetric allocation

Actually the ideal is not to do that, is to allocate the memory where you need that data, so it is easier to follow its flow and avoid forgetting to call the free(). Not doing this is practically asking to create confusion, gets asymmetrical.

Each function must be "owner" of its object in full (malloc() and free() should come in pairs, it should be declared, allocated and released on my site. All C Apis and any C programmer that understands the problem work that way. Function should not allocate memory to return to others, it should receive one buffer allocated to manipulate it.

Of course you have a case to allocate in your own place, but you can only use this if you know very well what you are doing, have a very strong reason and know that you will have to pay close attention to manage the memory.

Warnings

Warnings are errors that do not prevent the compilation, only that. The fact that it does not seem an error does not mean that it is not.

  • I got it here, thanks, I just had to switch vector from 4 to pointer there on malloc. In case the release will be made in the variable that receives the return? Example : Vertice *points = getPointsFromFace(c, c.faces[i]) .... free(points)

  • That’s right. I didn’t understand what had to change.

  • Of int vertices[4] = malloc(4 * sizeof(int)); for int *vertices = malloc(4 * sizeof(int));

  • 1

    Ah, that’s right, I ate ball right there.

Browser other questions tagged

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