malloc() in C - Source Code Example

In this source code example, we will see how to use the malloc() function in C programming with an example.

malloc() Function Overview

The malloc() function stands for "memory allocation" in C. It's used to allocate a block of memory of a specified size at runtime. It's part of the <stdlib.h> library. 

The memory allocated using malloc needs to be released using free() to prevent memory leaks.

Source Code Example

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

int main() {
    int *arr;
    int n, sum = 0;

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

    // Allocating memory for 'n' integers
    arr = (int*)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!");
        exit(1);
    }

    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Calculating the sum of the integers
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }

    printf("Sum = %d\n", sum);

    // Releasing the allocated memory
    free(arr);

    return 0;
}

Output

Enter number of elements: 4
Enter 4 integers:
1 2 3 4
Sum = 10

Explanation

1. We first prompt the user to enter the number of integers they want to store.

2. We use malloc to allocate a memory block that can store 'n' integers.

3. We check if the memory allocation was successful. If not, we print an error message and exit.

4. We then prompt the user to enter 'n' integers.

5. After storing these integers in the memory block, we calculate and print their sum.

6. Finally, we release the allocated memory using free() to ensure there's no memory leak.


Comments