Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to use free on a pointer but not a normal declaration?

Tags:

c

pointers

free

Why do I have to use free() when I declare a pointer such as:

int *temp = (int*)malloc(sizeof(int))
*temp = 3;

but not when I do:

int temp = 3;
like image 803
samoz Avatar asked Mar 09 '09 17:03

samoz


1 Answers

Normal declarations are put on the stack. When the function returns the stack pointer reverts to the value it had before the function was called, so the memory is automatically reclaimed.

Malloc-based declarations are allocated from the 'heap', which requires the programmer to manage allocations and deallocations.

like image 174
Alnitak Avatar answered Oct 23 '22 07:10

Alnitak