Skip to content

Working with dynamic memory

Rafiul Islam edited this page Oct 31, 2018 · 2 revisions

Dynamic memory allocation functionality defined at stdlib.h

What is dynamic memory allocation?

Memory can be allocated to store data in two way:

  • static
  • dynamic

When compiler compile a program it will allocated needed memory according to defined variable in the code. When a variable defined in static way then it's memory size can't be change in program running time. Suppose to store a sequential data an array of 10 length is created. But on program run time there are more then item have to store in this array, but if the array is defined in static way then it can't be possible to increase the length of the array during program run time. Because the compiler allocated 10 indices for this array and this is fixed.

To solve this kind of problem the variable should be defined in dynamic way. Because dynamic memory can be allocated and release during program run time.


Standard Library functions

To allocated new memory

  • malloc
  • calloc

To reallocate a variable memory

  • realloc

To release a memory

  • free

malloc

(type_cast*) malloc(byte_size);

This will return a pointer of allocated memory for access location. Initially memory will filled with garbage value. The pointer point on starting address of the allocated memory.

     int *pointer1 = (int*)malloc(16); // allocate 16 byte
     int *pointer2 = (int*)malloc(size_of(int)*4); // allocate 4 block of integer size

calloc

(type_cast*) calloc(quantity, block_size);

Functionality are same as malloc. calloc provide the way to allocate memory with 2 parameter.

  • block_size size of each block of data; for integer it will be 4 byte
  • quantity total number block;

This will return the starting index of allocated memory. Initially memory is filled with 0.

    int *pointer1 = (int*)calloc(4,size_of(int));

realloc

(type_cast*) realloc(pointer_of_previous_location, new_size);

This will return this pointer with a new allocated memory block. Like previous this pointer has 20byte, now if this command will request for 30byte then program will manage 10byte more and add with previous.

free

free(pointer);

This will free the allocated memory block of this pointer.