When I alloc memory outside a while loop for example, is it okay to free it inside it ? Are these two codes equivalent ?
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
free(memory);
}
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
}
free(memory);
Yes, they are equivalent. You do not have to call free()
if allocation did not succeed.
Pay attention, that memory
is pointer to int
and you have to dereference it to assign something to its memory block;
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory)
*memory=10;
free(memory);
memory = NULL;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With