Functions malloc, calloc, realloc and free are used to allocate /deallocate memory on heap in C/C++ language. These functions should be used with great caution to avoid memory leaks and dangling pointers. How are these functions different (or similar)?
Those who use languages like C and C++ that support user defined pointer variables, put utmost emphasis on implementing the pointers correctly. And rightfully so, A pointer wrongly handled can be catastrophic. And that’s an understatement 🙂 .
In my earlier articles on C++, I have written about the automatic type detection, uniform initialization list and Range based for loopin C++11. Earlier we used to use the NULL macro which is synonymous to int zero. This came as an inheritance from C language where 0 plays a double role (as an int and as NULL […]
Yesterday we learned about how to allocate memory on heap for an n-dim array using Malloc. Today let us see how to deallocate the memory on heap using free. It is Simple if we are deallocating normal pointers or pointers pointing to a one-dimensional array. How will deallocate memory of an n-dim array on heap?
Dynamic arrays are on heap. If an array is stored on heap, its address must be stored in pointer variables, else there will be no way to access the array. Let us assume the Array to hold integers. Write a code to allocate memory to a 2-dim array and then generalize it to allocate memory […]