Dynamic Memory Allocation Explained With Simple Example

Dynamic memory allocation is the process of allocating memory at run time by the program based on the need of the program. Dynamic Memory allocation is done from the heap memory available in the system and handling of memory (creation and deletion) is totally handled by the programmer. In case, programmer forgets to cleanup the allocated dynamic memory block, it will lead into memory leak and this memory block will be blocked for further use until program restarts.

Methods available to allocate dynamic memory at run time are

  • malloc () – allocates one memory block of requested size.
  • calloc () – allocates multiple blocks of memory and initialize it with 0.
  • realloc () – increases or decreases the size of previously allocated memory block.
  • free () – frees the memory allocated by above functions.
(more…)
Dynamic Memory Allocation Explained With Simple Example Read More

new vs malloc and free vs delete explained with simple example

malloc() and free() are the library functions provided by the C which can be used to allocate and deallocate memory at runtime, whereas new and delete are the the operators provided by C++ which can be used to allocate and deallocate memory at runtime.
The basic difference between new and malloc() is that memory allocation using new calls the constructor which initializes the memory. In case of malloc(), returned memory is uninitialized and needs to be initialized explicitly.
Similarly, deallocating memory using delete calls the destructor and hence allowing to do a proper cleanup whereas in case of free(), destructors are not called and hence cleanup needs to be done prior free() call. Let’s look into some more difference between these functions.

(more…)
new vs malloc and free vs delete explained with simple example Read More