A Dynamic Array in C programming is a variable-sized array whose memory size is allocated at runtime from the Heap rather than at compile-time on the Stack. Unlike static arrays with fixed dimensions (such as int arr[100];), dynamic arrays allow programmers to request exactly the amount of memory needed and resize it on the fly using standard C memory management functions: malloc(), calloc(), realloc(), and free().
Feature |
Static Array |
Dynamic Array |
|---|---|---|
Memory Location | Stack segment | Heap segment |
Size Determination | Compile-time (fixed constant) | Run-time (user input) |
Resizability | Cannot be resized | Can be grown/shrunk via |
Deallocation | Automatic when out of scope | Manual via |
Memory Efficiency | Can cause memory wastage or stack overflow | Optimal memory utilization |
Dynamic memory is requested using a pointer and the malloc() function declared inside <stdlib.h>:
int *arr;
int n = 5;
/* Allocate memory for 5 integers */
arr = (int*) malloc(n * sizeof(int));
/* CRUCIAL: Always verify if allocation succeeded */
if (arr == NULL) {
printf("Memory Allocation Failed!\n");
exit(1);
}
realloc()When an array runs out of space, the realloc() function expands or contracts the existing block without losing its prior data:
/* Resize array from 5 to 10 elements */
int *temp = (int*) realloc(arr, 10 * sizeof(int));
if (temp != NULL) {
arr = temp; /* Successfully reallocated */
}
This complete program accepts n initial numbers, dynamically doubles the array size, appends extra numbers, and deallocates memory:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr, n, i, new_size;
printf("Enter initial number of elements: ");
scanf("%d", &n);
/* 1. Allocate initial dynamic array */
arr = (int*) malloc(n * sizeof(int));
if(arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter %d integers:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
/* 2. Display initial elements */
printf("\nInitial Dynamic Array: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
/* 3. Resize array to hold additional elements */
new_size = n + 2;
arr = (int*) realloc(arr, new_size * sizeof(int));
if(arr == NULL) {
printf("Reallocation failed!\n");
return 1;
}
printf("\nEnter %d more integers:\n", 2);
for(i = n; i < new_size; i++) {
scanf("%d", &arr[i]);
}
/* 4. Display combined array */
printf("\nExpanded Dynamic Array: ");
for(i = 0; i < new_size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
/* 5. Clean up memory */
free(arr);
arr = NULL; /* Prevent dangling pointer */
printf("\nMemory successfully freed.\n");
return 0;
}
Never forget free(): Forgetting to release allocated heap memory causes Memory Leaks, eventually slowing down or crashing your system.
Reset pointers to NULL: After calling free(ptr), set ptr = NULL; to avoid accessing a dangerous dangling pointer.
Always check for NULL: Operating systems may deny allocation requests if RAM is exhausted.
Review these dry-runs, multiple-choice questions, and lab challenges to master heap memory in C.
Part 1: Spot the Bug & Predict the Output
Problem 1: What is the fatal bug in this code snippet?
void createArray() {
int *p = (int*)malloc(100 * sizeof(int));
/* Some operations */
}
int main() {
createArray();
return 0;
}
Answer & Explanation: Memory Leak! The pointer p is a local variable inside createArray(). When the function returns, p is destroyed from the stack, but the 400 bytes on the heap remain allocated with no remaining pointer referencing them. The memory cannot be freed.
Part 2: Multiple Choice Questions (BCA Exam Special)
Q1. Which library header must be included to use malloc() and free()?
A) <stdio.h>
B) <stdlib.h>
C) <string.h>
D) <conio.h>
Correct Answer: B) <stdlib.h>.
Q2. What does malloc() return if there is insufficient memory available?
A) 0 (NULL pointer)
B) -1
C) A garbage pointer
D) Terminates program automatically
Correct Answer: A) NULL.
Q3. What is the key difference between malloc() and calloc()?
A) malloc() is faster and initializes memory to zero
B) calloc() initializes all allocated bytes to zero; malloc() leaves garbage values
C) calloc() allocates on stack; malloc() on heap
D) There is no difference
Correct Answer: B) calloc() initializes memory to zero; malloc() leaves garbage values.
Part 3: Hands-on Lab Assignments for Beginners
Assignment 1: Write a C program to find the sum and average of N floating-point numbers stored in a dynamically allocated array.
Logic Hint: Read n, allocate using float *arr = (float*)malloc(n * sizeof(float));, iterate with a loop, and calculate sum.
Part 4: Frequently Asked University Viva Questions
1. What is heap memory in C?
Answer: The heap is an unstructured pool of free memory managed by the operating system, used by programs for dynamic runtime memory allocation.
2. Can realloc() move the allocated block to a completely new memory location?
Answer: Yes. If there is not enough contiguous memory adjacent to the existing block, realloc() copies the data to a new location with sufficient space, frees the old block, and returns the new pointer.