C malloc function

malloc stands for memory allocation. It is used to allocate a block of memory of a specified size at runtime. The memory is not initialized, so its contents are garbage (whatever was previously in that memory location).

Syntax:


void* malloc(size_t size);

Explanation:

1. size: The number of bytes you want to allocate.

2. Returns a pointer to the allocated memory if successful, or NULL if the allocation fails.

Example:


int* arr = (int*) malloc(10 * sizeof(int));  // Allocates memory for 10 integers

Explanation:

In this example, malloc allocates enough memory to store 10 integers (since sizeof(int) is the size of one integer).

Complete Example:


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

int main() {
    // Step 1: Allocate memory for an array of 10 integers using malloc
    int* arr = (int*) malloc(10 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Step 2: Initialize the array
    for (int i = 0; i < 10; i++) {
        arr[i] = i * 10;  // Fill array with some values
    }

    // Step 3: Print the array
    printf("Array values (after malloc): ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:

Array values (after malloc): 0 10 20 30 40 50 60 70 80 90