Memory Allocation in Data Structures B.Tech Notes 2025 Static vs Dynamic

n the study of data structures for B.Tech and BCA students, the concept of memory allocation forms a foundational pillar. Efficient memory allocation ensures optimal utilization of system resources and directly impacts the performance of any software application. This chapter provides in-depth coverage of memory allocation strategies in data structures, with a focus on static memory allocation and dynamic memory allocation, tailored specifically to the B.Tech Data Structures Notes 2025 and Unit 2 Notes Data Structures syllabus.

Memory allocation refers to the process of assigning blocks of memory to various parts of a program. This memory is used to store data variables, function calls, objects, and other components necessary for program execution. The memory assigned to a program can either be predetermined at compile time or determined at runtime. This distinction leads to the two major types of memory allocation — Static Memory Allocation and Dynamic Memory Allocation.

Static memory allocation is the method by which memory is assigned to variables at compile time. It is predictable, and the memory requirement must be known in advance. On the other hand, dynamic memory allocation assigns memory during runtime, allowing a program to utilize memory more flexibly and efficiently, especially in scenarios where the amount of memory required is not known before execution. The dynamic approach also supports complex data structures like linked lists, trees, and graphs that expand or contract during execution.

Static Memory Allocation

In static memory allocation, all variables and data structures are allocated memory before the execution of the program begins. This means the memory is set aside at compile time and remains allocated throughout the program’s lifetime. Static memory allocation is used when the amount of memory required is fixed and known in advance. This method is faster because memory is pre-allocated and does not require frequent allocation and deallocation.

Static memory is typically allocated in the stack or the data segment of the memory. The stack is used for local variables, while global and static variables reside in the data segment. This kind of allocation is particularly suited for array-based structures where the size is predetermined.

Advantages of Static Memory Allocation:

  • Faster access due to compile-time memory layout.
  • No fragmentation occurs since memory remains fixed.
  • Simplified memory management as allocation and deallocation are handled automatically by the compiler.

Limitations of Static Memory Allocation:

  • Wastage of memory if allocated size is larger than required.
  • Inflexible for data structures whose size changes dynamically.
  • Requires prior knowledge of memory requirements.
ASCII Representation of Static Memory Allocation:

+----------------------+------------------------+
| Variable Name        | Memory Address         |
+----------------------+------------------------+
| int a[10]            | 0x1000 - 0x1028        |
| float b              | 0x102C                 |
+----------------------+------------------------+

Dynamic Memory Allocation

Dynamic memory allocation enables programs to request memory during runtime based on actual requirements. This allocation occurs in the heap segment of memory and is managed through standard library functions like malloc(), calloc(), realloc(), and free() in C, and through new and delete in C++.

This approach is especially crucial in implementing non-linear and adaptive data structures such as linked lists, binary trees, stacks, and queues. As data grows or shrinks, memory is allocated or freed accordingly, optimizing memory utilization and supporting scalability.

Key Dynamic Allocation Functions in C:

  • malloc(size): Allocates size bytes of memory and returns a pointer to the first byte.
  • calloc(n, size): Allocates memory for n elements each of size bytes and initializes them to zero.
  • realloc(ptr, size): Changes the size of memory block pointed to by ptr to size bytes.
  • free(ptr): Deallocates the memory previously allocated by any of the above functions.

Advantages of Dynamic Memory Allocation:

  • Memory is used efficiently as it is allocated only when needed.
  • Supports dynamic and flexible data structures.
  • Allows variable memory size during runtime.

Limitations of Dynamic Memory Allocation:

  • Slower access compared to static allocation.
  • Risk of memory leaks if free() is not used properly.
  • More complex to manage and debug due to manual allocation/deallocation.
ASCII Diagram for Dynamic Memory Allocation:

+----------------------+------------------------+
| Operation            | Heap Memory State      |
+----------------------+------------------------+
| malloc(10*sizeof(int))| 0x2000 - 0x2028        |
| free(ptr)            | Memory released        |
+----------------------+------------------------+

Comparison Table: Static vs Dynamic Memory Allocation

FeatureStatic Memory AllocationDynamic Memory Allocation
Allocation TimeCompile-timeRuntime
FlexibilityFixedFlexible
Memory UsageMay lead to wastageEfficient
Data Structure SuitabilityArraysLinked Lists, Trees
Memory AreaStack, Data SegmentHeap
DeallocationAutomaticManual (using free())
Risk of Memory LeakNoYes, if not properly freed

Use Cases and Examples

Let us consider a few examples to understand when to use static or dynamic memory allocation. Suppose a program is designed to store the marks of exactly 100 students. In such a scenario, static memory allocation using an array is ideal:

int marks[100];

However, if the program needs to handle marks of an unknown number of students that may be entered by the user during runtime, dynamic memory allocation is preferable:

int *marks;
int n;
printf("Enter number of students: ");
scanf("%d", &n);
marks = (int*)malloc(n * sizeof(int));

Here, the memory is only allocated based on actual requirement, ensuring better memory usage.

Memory Management in Dynamic Allocation

Efficient dynamic memory management requires a good understanding of pointers and memory layout. Errors such as dangling pointers, double free, and memory leaks are common and must be handled carefully. Dangling pointers occur when memory is freed but the pointer still points to that memory location. Double freeing happens when free() is called twice on the same memory address, leading to undefined behavior.

To avoid these issues:

  • Always set pointers to NULL after freeing.
  • Track all allocated memory blocks.
  • Use memory debugging tools like Valgrind.
ASCII Diagram: Dangling Pointer

Before free():
ptr ---> [Memory Block 0x3000]

After free():
ptr ---> [Freed Memory Block] (Still Accessible) ❌

Solution: ptr = NULL;

Impact on Data Structures

Static memory allocation limits the adaptability of data structures. For instance, arrays require a fixed size and cannot grow beyond their declared capacity. Conversely, dynamic memory allows implementation of more flexible structures. A linked list is an example where each node is dynamically allocated:

struct Node {
  int data;
  struct Node* next;
};

struct Node* head = (struct Node*)malloc(sizeof(struct Node));

This type of allocation supports insertion and deletion of elements at any point, unlike arrays which require shifting elements.

📌 Insert Diagram: Singly Linked List Using Dynamic Memory

Garbage Collection in High-Level Languages

Languages like Java and Python automate dynamic memory management through garbage collection. This process automatically detects unused objects and frees memory, preventing leaks. However, C/C++ programmers must manage memory manually, which is more error-prone but gives finer control over system resources.

Performance and Efficiency Considerations

When choosing between static and dynamic memory allocation, performance trade-offs must be considered. Static memory is faster due to its compile-time allocation and predictable access. Dynamic memory, though flexible, incurs overhead due to runtime allocation and pointer dereferencing. Hence, for performance-critical systems, a hybrid approach may be adopted — using static memory for core operations and dynamic memory for auxiliary data.


🔹 Short Answer Questions (2-3 Marks)

  1. What is static memory allocation? Static memory allocation assigns memory at compile time and remains fixed during the program’s execution.
  2. Mention two disadvantages of dynamic memory allocation. It is slower due to runtime allocation and poses risks like memory leaks and dangling pointers.
  3. What is malloc() used for in C? malloc() is used to allocate memory dynamically during runtime.
  4. Differentiate between heap and stack memory. Stack memory is used for static allocation and local variables, while heap memory is used for dynamic allocation.
  5. What are memory leaks? Memory leaks occur when dynamically allocated memory is not properly deallocated, leading to wastage.
  6. What is a dangling pointer? A dangling pointer points to a memory location that has already been deallocated.
  7. Name two functions used for dynamic memory allocation in C. malloc() and calloc().

🔸 Long Answer Questions (5-10 Marks)

  1. Explain the difference between static and dynamic memory allocation with examples. Static memory allocation occurs at compile time and is fixed, while dynamic allocation occurs at runtime and is flexible. Static memory is suitable for arrays with fixed sizes, e.g., int arr[50];, while dynamic memory is used for variable sizes, e.g., int *arr = malloc(n * sizeof(int));.
  2. Discuss how memory is managed in dynamic memory allocation in C. What are the risks and how can they be avoided? Dynamic memory in C is allocated using malloc(), calloc(), and resized with realloc(). The memory must be released using free() to prevent leaks. Risks include memory leaks and dangling pointers. Best practices include setting freed pointers to NULL and tracking allocations carefully.
  3. Describe the role of dynamic memory allocation in implementing data structures like linked lists. Dynamic allocation enables creation of nodes at runtime, allowing linked lists to grow and shrink as needed. Each node is created using malloc(), and pointers link them. This allows efficient insertions and deletions without shifting elements like in arrays.
  4. What are the major differences in memory layout between static and dynamic allocations? Include diagrams. Static memory uses stack/data segment, while dynamic memory uses heap. Static is contiguous and fixed, dynamic is non-contiguous and adjustable. Diagrams can show memory blocks allocated at compile vs runtime.
  5. Explain the use and significance of calloc() and realloc() functions with examples. calloc() allocates and initializes memory to zero, useful when default initialization is required. realloc() changes the size of an existing block, aiding in expanding/shrinking memory during execution.

📝 Chapter Summary Memory allocation is crucial in programming Static memory allocation occurs at compile time and uses stack or data segment Dynamic memory allocation occurs at runtime and uses heap memory Static allocation is fast but inflexible Dynamic allocation is flexible but complex Static structures include arrays, dynamic structures include linked lists malloc(), calloc(), realloc(), and free() are used in C for dynamic memory Improper dynamic memory usage can cause leaks and dangling pointers Use static allocation when size is known, dynamic when it’s not


📘 Model Paper / Sample Internal Exam Questions

  1. Define static memory allocation. Mention one advantage and one disadvantage.
  2. Explain the purpose of malloc() and free() functions in C.
  3. Describe the differences between stack and heap memory with examples.
  4. Discuss the role of dynamic memory allocation in creating linked lists.

Leave a Reply

Your email address will not be published. Required fields are marked *