BCA SCHOOL
Programming Tutorials • Notes • Practical • Books
LATEST TUTORIALS

Standard Library Functions in C: abs, exit, free, rand | Unit 3 | BKNMU BCA

by BCA School



BKNMU Junagadh  |  BCA Sem 1  |  Unit 3

Standard Library Functions in C: abs, exit, free, and rand

Comprehensive Guide to General Utilities, Memory Deallocation, Math Offsets, and Pseudo-Random Numbers

BKNMU Junagadh BCA Sem 1 Unit 3 stdlib.h Header Memory & Process Control Dynamic Deallocation
In simple words: The <stdlib.h> header (C Standard General Utilities Library) provides essential low-level helper routines required by nearly every real-world program. It defines operations for integer mathematics (abs()), abnormal or normal program termination (exit()), heap memory deallocation (free()), and pseudo-random number generation (rand()). This guide details all four functions specifically prepared for BKNMU BCA Semester 1 (Unit 3).
📖 Core Categories of stdlib.h Functions

The general utility header organizes fundamental operations across four distinct systems:

abs()

1. Integer Arithmetic

Computes the absolute (positive) magnitude of an integer number by stripping negative signs without type conversion.

exit()

2. Process Termination

Terminates the active program immediately, flushes open file buffers, closes streams, and returns an exit status code to OS.

free()

3. Heap Memory Release

Deallocates memory blocks previously allocated by malloc, calloc, or realloc, returning heap space back to operating system.

rand()

4. Pseudo-Random Numbers

Generates a pseudo-random integer sequence ranging between 0 and RAND_MAX (at least 32767) for simulations and games.

1️⃣ Master Table: Function Specifications

A complete reference of function prototypes, operational behavior, and return values:

Function Prototype Functional Purpose Return Value / Type
int abs(int n) Calculates the absolute value of the specified integer value n. Returns absolute value as positive int.
void exit(int status) Terminates the calling process after performing standard cleanup and stream flushing. Does not return (void); passes status code to host environment.
void free(void *ptr) Releases dynamically allocated heap memory block pointed to by ptr. Takes memory address pointer. Returns nothing (void).
int rand(void) Generates a sequence of pseudo-random integers using an internal algorithm seed. Returns integer between 0 and RAND_MAX.
ℹ️ Crucial Constants in stdlib.h:
  • EXIT_SUCCESS: Macro integer representing successful termination (typically 0).
  • EXIT_FAILURE: Macro integer indicating unsuccessful or abnormal termination (typically 1 or non-zero).
  • RAND_MAX: Constant integer representing the maximum possible value returned by rand() (minimum 32767 in Turbo C).
💻 Practical Code Examples

1. Integer Absolute Value and Random Range Generation (abs & rand):

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

int main() {
    int negative_val = -45;
    int absolute_val;

    // 1. Compute absolute value
    absolute_val = abs(negative_val);
    printf("Original: %d | Absolute: %d\n", negative_val, absolute_val);

    // 2. Generate pseudo-random numbers between 1 and 100
    printf("Random Numbers: ");
    for (int i = 0; i < 5; i++) {
        int random_num = (rand() % 100) + 1;
        printf("%d ", random_num);
    }
    printf("\n");

    return 0;
}

2. Dynamic Memory Allocation and Process Termination (free & exit):

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

int main() {
    int *ptr;
    int n = 5;

    // Dynamic allocation on heap
    ptr = (int*) malloc(n * sizeof(int));

    // Check allocation failure and exit immediately if null
    if (ptr == NULL) {
        printf("Memory allocation failed! Exiting...\n");
        exit(EXIT_FAILURE); // Early program exit
    }

    printf("Memory successfully allocated at address: %p\n", ptr);

    // Deallocate heap memory to prevent memory leaks
    free(ptr);
    ptr = NULL; // Avoid dangling pointer
    printf("Memory successfully released with free().\n");

    exit(EXIT_SUCCESS);
}
🔄 Step-by-Step Flow: Memory & Process Lifecycle
1

Step 1: Allocation & Verification

The program requests heap memory. If the OS cannot provide contiguous blocks, exit() halts further operations to prevent memory corruption.

2

Step 2: Processing & Seed Usage

During runtime, abs() provides fast sign-independent calculations, while rand() computes values derived from algorithm seed states.

3

Step 3: Heap Cleanup & Exit Handler

Calling free() marks heap blocks available for reuse. Finally, exit() flushes buffered output and cleanly passes control back to the operating system.

💡 Critical Exam Difference: abs() vs fabs(): abs() is declared in <stdlib.h> and strictly handles integer types (int). For floating-point numbers (double or float), you must use fabs() declared in <math.h>.
⚠️ Danger: Dangling Pointer After free(): Calling free(ptr) frees the memory block, but the pointer variable ptr still holds the memory address. Always assign ptr = NULL; immediately after freeing to prevent accidental access to deallocated memory.
📝 Quick Revision — Key Exam Points
  • Header: #include <stdlib.h>
  • abs(n): Returns positive magnitude of integer n.
  • exit(status): Terminates program; 0 or EXIT_SUCCESS indicates success.
  • free(ptr): Releases heap memory; prevents memory leak bugs.
  • rand(): Generates numbers from 0 to RAND_MAX.
  • Formula for Range: To get numbers between min and max: (rand() % (max - min + 1)) + min.