Memory Management in C-Language

 

  Memory Management  

Dynamic Memory Allocation in C

  • The process of allocating memory at runtime is known as dynamic memory allocation.
  • Library routines known as memory management functions are used for allocating and freeing memory during execution of a program.
  • These functions are defined in stdlib.h header file.
FunctionDescription
malloc()allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
calloc()allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory
Freereleases previously allocated memory
reallocmodify the size of previously allocated space

Memory Allocation Process

  • Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in a memory area called Stack.
  • The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.

Allocating block of Memory

  • malloc() function is used for allocating block of memory at runtime.
  • This function reserves a block of memory of the given size and returns a pointer of type void.
  • This means that we can assign it to any type of pointer using typecasting.
  • If it fails to allocate enough space as specified, it returns a NULL pointer.
Syntax:
    void* malloc(byte-size)

calloc()

  • It is another memory allocation function that is used for allocating memory at runtime.
  • calloc function is normally used for allocating memory to derived data types such as arrays and structures.
  • If it fails to allocate enough space as specified, it returns a NULL pointer.
Syntax:
void *calloc(number of items, element-size)

realloc()

  • realloc() changes memory size that is already allocated dynamically to a variable.
Syntax:
    void* realloc(pointer, new-size)




No comments:

Post a Comment