1
Well given the following code is easy to do memory management:
Code Example (in C):
#include <stdio.h>
#include <stdlib.h>
int *criarValor(void){
int *valor = malloc(sizeof *valor);
*valor = 10;
return valor;
}
int main(void)
{
int *valorPtr;
valorPtr = criarValor();
/* Usa um ponteiro para acessar os valores */
printf("O valor na heap é: %d\n", *valorPtr);
/* Libera memória alocada */
free(valorPtr);
return 0;
}
But if dereferencing is done through the function itself? Is it possible (and/or necessary) to give free in the function? Follow the example of how such a case would be:
Doubt case (in C):
int *criarValor(void){
int *valor = malloc(sizeof *valor);
*valor = 10;
return valor;
}
int main(void)
{
/* Usa a própria função dereferenciada para acessar os valores */
printf("O valor na heap é: %d\n", *criarValor());
/* É correto dar esse free? A memória alocada
é corretamente liberada? */
free(criarValor());
return 0;
}
The doubt continues in C++:
Doubt code (in C++):
#include <iostream>
int *criarValor(void){
int *valor = new int(10);
return valor;
}
int main()
{
// Usa a própria função dereferenciada para acessar os valores
std::cout << "O valor no heap é : " << *criarValor() << std::endl;
// É correto dar esse deletada? A memória alocada
// é corretamente liberada?
delete criarValor();
}
The allocated memory is being released correctly?
In the last two examples, you allocate two values, but only release one.
– bfavaretto
How do I allocate two values? I just created a memory region that fits an integer.
– Rafael Bluhm
Each function call makes a distinct allocation, no?
– bfavaretto
The doubt is the second call, precisely in the
free (delete)
.– Rafael Bluhm
Look, I’m weak in C and absolutely ignorant in C++, but in my mind your free only releases the memory that was just allocated to the call you have in there. The call inside the printf made another allocation, and you can’t release that memory because you didn’t save the pointer returned on the first call.
– bfavaretto
That is the doubt.
– Rafael Bluhm
I think the point here is that each malloc call will allocate a new memory area, so in your code the line "free(createValor();" will free the memory allocated by the call to createValue that it is within the call to free and not the memory previously allocated by "printf("The value in the heap is: %d n", *createValue());",
– Selma