Dynamic Memory Allocation


Concept


Array declaration tells the compiler the memory that needs to be reserved for storing array elements.Compiler allocates this memory at compile time.(static allocation.) 
But this memory can sometimes be insufficient/more than needed.In order to avoid this,we can allocate memory during runtime.This is called as dynamic memory allocation(DMA).


Functions



You need to include stdlib.h or alloc.h to use these functions.

  • malloc()  
void* malloc(size_t size)
size_t = unsigned integer type used to represent the size of an object
Allocates memory of size bytes from memory heap and returns pointer to the 1st byte of newly allocated memory.This pointer is of type void*.It can be typecasted into pointer of any form.If memory can't be allocated it returns NULL.

In linked list we declare a node structure and we allocate memory for that structure at runtime.
typedef struct 
{
    int data;
    struct node* next;
}node;
 node* head = malloc(sizeof(node));

This will allocate memory equal to size of node and would return a pointer of type void* pointing to 1st byte of that memory.The pointer returned by malloc() is promoted to node* and assigned to head.So head points to newly allocated memory block.
         __________      
         |    |    |          
head---->|    |    |
         |____|____|     
          data next

  • calloc() 
This function allocates memory and clears it to 0.
void* calloc(size_t n,size_t size)
Allocates memory for n items of size bytes each and returns pointer to the 1st byte of newly allocated memory.This pointer is of type void*.
int* ptr = calloc(20,sizeof(int));
This will allocate memory for array of 20 integers.


  • realloc() 
void* realloc(void* prev,size_t newsize)

This function changes the size of the memory block whose address is prev to be new size.(previous size+size)

prev ---> points to a memory block previously obtained by calling malloc,calloc or                realloc.If it is a NULL pointer it works just as malloc.

newsize   --     New size in bytes for allocated block.

It adjusts the size of previously allocated block to newsize copying the contents to new location if necessary.
It returns the address of the reallocated block which might be different from the address of original block.
int* ptr = malloc(20,sizeof(int));
ptr = realloc(ptr,40);


  • free()
void free(void* ptr)
Deallocates memory block pointed by ptr previously allocated by malloc,calloc or realloc.
free(head);
Suppose head is a pointer pointing to a node,then the above statement would deallocate memory for the node pointed by head.This released memory is now available in the stock of memory.

No comments:

Post a Comment