NBC 103 • Unit 514 min readHigh Exam Frequency

Binary Search, Bubble Sort, malloc/free & File Handling

Unit 5: Searching, Sorting, Dynamic Memory & File HandlingProblem Solving Using C

👨‍🏫 Professor's Mental Model: Dictionary Searching & Renting Warehouse Space

Binary search dictionary dekhne jaisa hai: beech ka page kholo, agar word aage hai toh pichla aadha hissa fek do! Dynamic Memory (malloc) wedding hall book karne jaisa hai: jitne guests hain utni jagah lo, aur party khatam hone par hall khaali (free) kar do taaki memory leak na ho!

Searching & Sorting Algorithms

Linear Search: Sequential scan, O(N) time. Binary Search: Requires sorted array, repeatedly halves interval, O(log N) time. Bubble Sort: Compares adjacent elements and swaps if out of order, O(N^2) time. Selection Sort: Finds minimum element in unsorted subarray and moves to front, O(N^2) time.

Dynamic Memory Allocation (DMA) via <stdlib.h>

malloc(size): Allocates raw block of bytes containing garbage values. calloc(n, size): Allocates n contiguous elements initialized to ZERO. realloc(ptr, new_size): Resizes previously allocated heap block. free(ptr): Deallocates memory block to prevent Memory Leaks.

File Handling in C

Files accessed through FILE *fp pointers. Modes: 'r' (read), 'w' (write), 'a' (append), 'r+' (read/write). Key functions: fopen(), fclose(), fgetc(), fputc(), fprintf(), fscanf(), fread(), fwrite(), fseek().

Interactive Tested Code Example

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

int main(void) {
    int n = 5;
    int *arr = (int *)malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Heap allocation failed!\n");
        return 1;
    }
    
    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }
    
    printf("Dynamically Allocated Heap Array: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    
    // Free allocated memory
    free(arr);
    arr = NULL; // Prevent dangling pointer
    printf("Memory freed successfully.\n");
    return 0;
}
💡 Note:Demonstrates runtime heap allocation using malloc(), validating non-NULL return, accessing heap memory, and deallocating with free().

🎯 University Exam Scoring Blueprint

  • Always check if (ptr == NULL) after calling malloc() or calloc().
  • Binary search precondition: Array MUST be sorted in ascending or descending order.
  • Explain that EOF (-1) indicates End of File.

Top Viva Questions on Binary Search, Bubble Sort, malloc/free & File Handling

1 Questions
1

What is the key difference between malloc() and calloc()?