Search code examples
cmemorymalloccalloc

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

Solution

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