C++ free() function - An Ultimate Guide! With Examples

Hey, folks! In this article, we will be focusing on C++ free() function in detail. So, let us begin with it!!


What is C++ free() function?

C++ comprises various functions and operators to deal with memory management such as the new operator, malloc, etc.

C++ free() function enables the programmer to free up the memory space previously occupied by certain entity. That is, free() function de-allocates the memory blocks assigned to the entity for storage.

Thus, using free() function, we can make storage space available for further processing easily. Moreover, it enables us to empty the blocks of memory storage at dynamic runtime.

Let us now focus on the structure of free() function in the upcoming section.


Syntax of the free() function

Have a look at the below syntax!

The free() function accepts a pointer variable as an argument. This pointer variable is the pointer to the memory storage allocated to the pointed entity.

So, the free() function does not alter/change the value of the pointer variable i.e. the pointer will point to the same memory location which has be de-allocated and the memory has freed freed up!

IMP points to know!

  • The pointer variable should point to a memory block that has been allocated with malloc, realloc or calloc functions only otherwise, it results into an undefined behavior.
  • If a pointer variable is NULL, the free() does not perform any action on it.

Examples – C++ free() function

In the below example, we have used C++ calloc() function to dynamically assign memory storage to the given pointer variable.

Output:

Here, we have used malloc() function to allocate memory space at run time. Moreover, the free() function does not alter the address value of the pointer that points to the memory blocks as shown:

Output:


Conclusion

By this, we have come to the end of this topic. Feel free to comment below in case you come across any question.

Hope this article helps in having a clear understanding about the topic! 🙂

Till then, Stay tuned @ C++ programming with JournalDev and Keep Learning!!


References

By admin

Leave a Reply

%d bloggers like this: