When to free memory inside a C code?

nour02 picture nour02 · Jan 10, 2010 · Viewed 7.9k times · Source

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);

Answer

alemjerus picture alemjerus · Jan 10, 2010

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;