Dynamic Memory Allocation :

Memory Allocation :

Dynamic memory allocations refers to the method of allocating a block of memory and releasing it when the memory is not required at the time of running the program. A block of memory can be used to store values of simple or subscripted variables and a block of memory can be accessed using a pointer. Following are the functions used in dynamic memory allocation, and these functions are available in the header file <alloc.h> ( "alloc.h is a non-standard header file" ) .

Example :

  1. /* Description: simple memory allocation and after allocation complete free memory */
  2. #include<stdio.h>
  3. #include<string.h>
  4. main()
  5. {
  6. char *name;
  7. name = malloc(sizeof(char));
  8. if(name==NULL)
  9. {
  10. printf("allocate not completed.");
  11. }
  12. else
  13. {
  14. strcpy(name,"AyaN");
  15. }
  16. printf("allocated memory content : %s",name);
  17. free(name);
  18. getch();
  19. }

Output :

c language - simple memory allocation and after allocation complete free memory

malloc() Function :

malloc() function is used to allocate a single block memory to store values of specific data type. It also assigns the address of the first byte of the allotted space to a pointer.

Syntax :

ptr = (type *)malloc(size);

calloc() Function :

calloc() function is used to allocate memory in multiple block of same size during the program execution. The space alloted is used to store values of an array or structure.

Syntax :

ptr = (type *)calloc(n, m);

realloc() Function :

realloc() function is used to modify or re allocated the memory space which is previously allotted.

Syntax :

ptr = realloc(ptr, size);

free() Function :

free() function is used to release the memory space which is allotted using malloc(), calloc() or realloc() function.

Syntax :


Dangling pointer / Memory leak :

A dangling pointer is a pointer that does not point to a valid object and consequently may make a program crash or behave oddly. In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes