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

C malloc function – Interview Questions

Q 1: What does malloc() do?
Ans: Allocates a single block of memory.
Q 2: Does malloc() initialize memory?
Ans: No.
Q 3: What is the return type of malloc()?
Ans: void*.
Q 4: What happens if memory allocation fails?
Ans: It returns NULL.
Q 5: How do you allocate memory for 10 integers?
Ans: malloc(10 * sizeof(int));

C malloc function – Objective Questions (MCQs)

Q1. What does the malloc() function do?






Q2. What will malloc(0) return?






Q3. What is the syntax of malloc()?






Q4. What should be done after using malloc() allocated memory?






Q5. What will happen if there is not enough memory available for malloc()?






Related C malloc function Topics