Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to free memory inside a C code?

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);
like image 852
nour02 Avatar asked Dec 08 '22 04:12

nour02


1 Answers

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;
like image 127
alemjerus Avatar answered Jan 02 '23 01:01

alemjerus