How to use free()
function when it is used inside a function, in this function it generates a dynamic vector and itself will be the return of the function, eg:
int* copia(int *vet, int tam)
{
int i, *retorno;
retorno = (int*) malloc(tam * sizeof(int));
for(i = 0; i < tam; i ++)
retorno[i] = vet[i];
return retorno;
};
My question is how to release the retorno
vector properly, because Dev does not point to error, would it?
return retorno;
free(retorno);
In theory, you always have to release a dynamically allocated pointer and it should be released when its usage ends, but return
is usually used to finalize a function, so I was intrigued by so, if I put free
after return
, does it mean that it did not release my vector?
Because in theory , after return
the function to run, soon it would not read the free
underneath it, but also can not put free
before return
, because I'm still using the vector in line return
.
What's the right way?