Memory Allocation Checker
C
Easy
3 views
Problem Description
Allocate memory with malloc(). If NULL is returned (allocation failed) to handle the error, clean the memory that has already been allocated. Resource cleanup.
Official Solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr1 = NULL;
int *arr2 = NULL;
// First allocation
arr1 = (int *)malloc(100 * sizeof(int));
if (arr1 == NULL) {
printf("Memory allocation failed for arr1n");
return 1;
}
// Second allocation
arr2 = (int *)malloc(200 * sizeof(int));
if (arr2 == NULL) {
printf("Memory allocation failed for arr2n");
// Cleanup already allocated memory
free(arr1);
arr1 = NULL;
return 1;
}
// Use the memory
printf("Memory allocated successfully.n");
// Normal cleanup
free(arr2);
free(arr1);
arr2 = NULL;
arr1 = NULL;
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!