4
How to use function free()
when it is used within a function, in that function Gero a dynamic vector and the function itself will be the return, example:
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 vector retorno
correctly, because Dev does not point error, would be like this?
return retorno;
free(retorno);
In the theory you always have to release a dynamically allocated pointer and it must be released when it ends its use, but the return
is usually used to finalize a function, so I was intrigued by this, because if I put the free
after the return
means he didn’t release my vector?
Because in the theory, after return
the function stops rotating, so it would not read the free
underneath it, but I can’t put the free
before the return
, because I’m still using the vector on the line return
.
What’s the right way?
Thanks for clearing the doubt! Yes, it’s Dev C++, I know he’s problematic, but since in college he’s the only one installed I joined him to do the work, I remembered a day at a test, printing
8 + 2
he thought it was20
.. I will take a look at the link, I have installed the Code::Blocks, but its compiler is not working, I will do a search on the error and go to use it or look at others link.– Leonardo