2080 9

CSC115 ยท 2080 ยท 5 marks

What is dynamic memory allocation? Explain with a suitable program.

What is dynamic memory allocation? Explain with a suitable program. [5]

C ProgrammingChapter 9: PointersDynamic Memory Allocation

Quick answer

The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution.

Dynamic Memory Allocation

Definition

Problems with static allocation (e.g., int emp[100];):

  • If fewer values are stored, memory is wasted
  • If more values are needed, we cannot store them

Dynamic memory allocation solves both problems. Memory is accessed through pointers, and the functions are available in stdlib.h / alloc.h.


Key Functions

FunctionPurpose
malloc()Allocates a block of memory of specified size
calloc()Allocates memory and initializes to zero
realloc()Resizes previously allocated memory
free()Releases dynamically allocated memory

Syntax of malloc():

pointer_variable = (datatype *) malloc(specified_size);

Example Program

The following program dynamically allocates memory for n integers entered by the user, stores them, and displays them.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    int n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    /* Dynamically allocate memory for n integers */
    ptr = (int *) malloc(n * sizeof(int));

    /* Check if memory was allocated successfully */
    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    /* Input values */
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &ptr[i]);
    }

    /* Display values */
    printf("You entered:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    /* Release the allocated memory */
    free(ptr);

    return 0;
}

Sample Output

Enter number of elements: 4
Enter 4 integers:
10 20 30 40
You entered:
10 20 30 40

Key Points

  • malloc(n * sizeof(int)) allocates exactly the memory needed at runtime
  • The pointer ptr is used to access the dynamically allocated memory block
  • free(ptr) releases the memory back to the system after use
  • If allocation fails, malloc() returns NULL, which should always be checked

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.