Reputation: 57
I've read conflicting information on the internet about this. To the best of my knowledge all variables in a function only exist for the life time of the function and so this shouldn't be necessary. But with dynamic pointer arrays I'm not sure.
Thanks
Upvotes: 2
Views: 221
Reputation: 473
If you have allocated data using malloc/calloc, you need to free the data.
Addition due to curious comment by @Julia Childe:
Well, the point of allocating dynamic memory is that it will remain there till you explicitly free it. This enables you to pass pointers both from and to functions and you are not limited by the scope of a specific function, i.e. main. Thereby, you can allocate memory for data when you need to and not in advance, thus dynamic memory.
If we did not have this ability, we would have to know how much memory space we would use at compile time.
Hope this clears out some question marks.
Upvotes: 0
Reputation: 39164
It depends on where the memory referenced by the pointer has been allocated. There are fundamentally 2 ways of allocating space in C.
Using the stack :
void foo(){
int stack_variable = 10;
int *stack_pointer = &stack_variable; //bar shouldn't be freed.
}
Using the heap:
void foo(){
int * heap_pointer = (int *) malloc(sizeof(int)); //heap_pointer need to be freed somewhere
}
In the first case there is no problem: memory allocated in the stack will be released when the function returns. Even if you are using a pointer, and it points to some data in the stack, free isn't necessary. Be careful to not use a pointer to data allocated in the stack when the data itself goes out of scope:
int * foo(){
int stack_variable = 10;
int *ptr = &stack_variable;
return ptr;
}
int * ptr = foo(); // you have a problem here: ptr points to a memory region that no longer exist!
In the second case you are using the heap so you need to use free somewhere, to explicitly release it.
Upvotes: 1
Reputation: 24561
You don't free pointers - they are cleaned up automatically. What you need to free is the memory that was acquired by malloc. You use pointers to access that memory.
Upvotes: 4
Reputation: 36049
Put laconically: Every pointer you get from malloc
has to go to free
exactly once. Nothing more, nothing less.
Upvotes: 1