What happens to a local pointer variable inside a function that has been dynamically allocated?

Viewed 1202

I'm curious to know what happens if you declare an int pointer inside a function, and then dynamically allocate it using malloc

void testing(){
   int *p = malloc(sizeof(int));
   *p = 5;
}

Does the data (5 in this case) live on in the heap even though the pointer is destroyed after the function is finished executing?

3 Answers

Does the data (5 in this case) live on in the heap even though the pointer is destroyed?

Yes, it is called memory leak. You allocated memory and stored its reference in pointer p, when p is destroyed you lost only the reference to allocated memory introducing a memory leak.

Memory allocated using malloc() or calloc() is not freed automatically. You have to call free() explicitly to de-allocate the memory.

// Allocate
int* p = (int*)malloc(10 * sizeof(int)); 

// De-allocate
free(p);

In this function

void testing(){
   int *p = malloc(sizeof(int));
   *p = 5;
}

the local variable (pointer) p has the automatic storage duration.

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.(the C Standard).

The object that occupies the allocated memory with malloc has the allocated memory duration.

The lifetime of an allocated object extends from the allocation until the deallocation. (the C Standard).

So as the memory was not explicitly deallocated then the lifetime of the object extends until the program will be finished. You can not access the object or reuse the allocated memory because the address of it stored in the local variable p is lost after exiting the function. This situation invokes a memory leak.

Related