What is the meaning of the term free function in C++?
The term free function in C++ simply refers to non-member functions. Every function that is not a member function is a free function.
struct X {
void f() {} // not a free function
};
void g() {} // free function
int h(int, int) { return 1; } // also a free function
Correct usage of free() function in C
You should call free only on pointers which have been assigned memory returned by malloc
, calloc
, or realloc
.
char* ptr = malloc(10);
// use memory pointed by ptr
// e.g., strcpy(ptr,"hello");
free(ptr); // free memory pointed by ptr when you don't need it anymore
Things to keep in mind:
Never free memory twice. This can happen for example if you call
free
onptr
twice and value ofptr
wasn't changed since first call tofree
. Or you have two (or more) different pointers pointing to same memory: if you call free on one, you are not allowed to callfree
on other pointers now too.When you free a pointer you are not even allowed to read its value; e.g.,
if (ptr)
not allowed after freeing unless you initializeptr
to a new valueYou should not dereference freed pointer
Passing null pointer to
free
is fine, no operation is performed.
How does free know how much to free?
When you call malloc()
, you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you :-).
When you call free()
, it simply looks at the extra information to find out how big the block is.
How does free function on pointer in C work?
Read a lot more about undefined behavior (UB). Your code has some (you are not allowed to do something with a pointer after it has been free
-d).
Even after I free the pointer, why is it still giving 25 as output?
It is UB. You have bad luck. Be scared.
Read the C11 standard specification n1570.
You don't really need to understand how free
works (but you need to understand how you should use it). However, it usually uses some operating system specific system call dealing with virtual address space. On Linux, many C standard library implementations -e.g. GNU glibc or musl-libc - are free software (so you can download and study their source code), and their malloc
might sometimes get more virtual address space with system calls like mmap(2) (or the old sbrk(2)), and their free
might sometimes release some space with munmap(2).
What usually happens is that C dynamic memory allocation works differently for "large" and "small" memory zones. For small zones, the C library prefer to re-use previously free
-d ones in future malloc
-s. It gets (sometimes) from the OS a large chunk of memory (using mmap
) and split that chunk into pieces. When you free
a small zone, that zone is simply added to some collection of pieces, for future malloc
. So it still "exists" but using it is UB (and that explains the behavior your are observing).
The valgrind utility is a very useful tool to hunt memory related UB.
Question about free function and memory allocation ( C )
Nope, free
won't deallocate more than the allocated pointer passed to it. The correct answer from your list is 3. free
will deallocate the memory pointed by a
at that point in time and that's it. It won't fill that memory zone with zero or anything else.
Also, when you readArray(5)
, you create allocate new memory and leave aside the old allocated one before. So what you are doing step-by-step:
- Allocated some memory (let's call it
X
) usingmalloc
and store its address in variablea
. - Call
readArray
which will allocate some other memory (let's call itY
) and store its address ina
. - Free the memory which is stored in
a
, which is theY
allocated memory chunk.
Now the memory labeled X
will be dangling, meaning that you don't have any reference to it and you have no ways of deallocating it. It's just allocated memory which cannot be reached anymore, as you lost the pointer to it.
Related Topics
"Incomplete Type" in Class Which Has a Member of the Same Type of the Class Itself
When Should I Use C++ Private Inheritance
What Requirements Must Std::Map Key Classes Meet to Be Valid Keys
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++
How to Implement Atoi Using Simd
Executing Cv::Warpperspective For a Fake Deskewing on a Set of Cv::Point
Is It Safe to Assume That Stl Vector Storage Is Always Contiguous
How to Convert a Lambda to an Std::Function Using Templates
"Invalid Use of Incomplete Type" Error With Partial Template Specialization
Generate Random Numbers Following a Normal Distribution in C/C++
Fastest Way to Get Ipv4 Address from String
Std::String to Float or Double
Why Should the System() Function Be Avoided in C and C++
Is 0 a Decimal Literal or an Octal Literal
C++ Call Pointer to Member Function
How Does Photoshop Blend Two Images Together