Nepal's open education portal

EduNepalEduNepal
Long10 markshardSolution

Explain dynamic memory allocation in C. Differentiate between `malloc()` and `calloc()`. Write a C program to dynamically allocate memory for N integers, sort them in ascending order, and free the memory.

C Programming

Verified Solution & Step-by-Step Explanation

solution · en · Verified by Editorial Board

Dynamic Memory Allocation in C

Dynamic memory allocation allows programs to request memory from the operating system heap during runtime rather than compile time.

malloc() vs calloc()

  1. malloc(size): Allocates a single contiguous block of memory of specified bytes. Contains garbage values.
  2. calloc(n, size): Allocates n blocks of memory, each of size bytes, and initializes all allocated bytes to zero.

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

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

int arr = (int) malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; }

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

// Bubble Sort for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }

printf("Sorted array in ascending order:\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");

free(arr); // Deallocate arr = NULL; return 0; } ```