Welcome

C Programming Tutorial


C Dynamic Memory Tutorial

     Dynamically Allocating memory for data structures is required for data structures whose is size is not known in advance. Dynamic memory allocation done at RAM(Randon Access Memory) memory and also known as "Heap" memory. Allocation and Deallocation done by programmer. Whereas local variables,function parameters,constants etc., are all stored in stack memory area. Whenever their scope ends, they are automatically poped/erased from stack. Where as in Dynamic memory allocation, its programmer's job to clean up the memory.

Dynamic Memory Allocation can be done using following functions

  • malloc -memory allocation
  • ,
  • calloc-contiguous allocation
  • ,
  • realloc - reallocation
When no longer needed,dynamic memory can be freed with free function call

malloc function

syntax:   void *malloc(size_t size)

malloc function allocates block of memory specified by size bytes. The space is not initialized. A successful call returns the base address of the allocated space. otherwise if it fails to allocate required size,it return NULL.

calloc function

syntax:   void *calloc(size_t size,size_t el_size)

calloc function allocates contiguous space in memory for an array of size elements, where each element requires size el_size bytes . The space is initialized with zeros. A successful call returns the base address of the allocated space. otherwise if it fails to allocate required size,it return NULL.

realloc function

syntax:   void *realloc(void*ptr,size_t size)

realloc function changes size of the memory block to size bytes.
if size bytes greater than the previous block ,old memory block content is unchanged,new one's are unitialized.
if size bytes less than the previous bytes, it frees remaining memory.
A successful call returns the base address of the allocated space. otherwise if it fails to allocate required size,it return NULL.

ADS