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:
C malloc function – Interview Questions
Q 1: What does malloc() do?
Q 2: Does malloc() initialize memory?
Q 3: What is the return type of malloc()?
Q 4: What happens if memory allocation fails?
Q 5: How do you allocate memory for 10 integers?
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()?