CSC115 C Programming

C ProgrammingTU Board 2080Unit 9

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

5

Answer

Dynamic memory allocation means reserving memory while the program is running, instead of fixing its size when the program is written. The memory comes from the heap, and the program must release it when it no longer needs it.

It is useful when the amount of data is only known at run time, for example when the user decides how many numbers to enter.

C provides four functions in <stdlib.h>:

Function What it does
malloc(size) Allocates size bytes. The contents are not initialised.
calloc(n, size) Allocates n elements of size bytes each and sets every byte to 0.
realloc(ptr, size) Changes the size of a block allocated earlier, keeping its contents.
free(ptr) Releases a block so the memory can be reused.

All three allocating functions return NULL if there is not enough memory, so the result must always be checked.

Program: read n numbers into a dynamically allocated array and find their sum

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

int main(void) {
    int n, i, sum = 0;
    int *a;

    printf("How many numbers? ");
    scanf("%d", &n);

    a = (int *)malloc(n * sizeof(int));   /* memory for n integers */
    if (a == NULL) {
        printf("Memory not available\n");
        return 1;
    }

    for (i = 0; i < n; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &a[i]);
        sum += a[i];
    }
    printf("Sum = %d\n", sum);

    free(a);                              /* give the memory back */
    return 0;
}

Here the array size is decided by the user at run time, which is impossible with an ordinary array like int a[100]. Forgetting free() causes a memory leak, and using the pointer after free() is a dangling pointer error.

Discussion

Loading…

More C Programming questions

All C Programming old questions