C stdlib.h Header
Standard library functions for memory and utilities
🔧 What is stdlib.h?
The stdlib.h header provides essential utility functions including memory allocation, program control, conversions, and random number generation. It's fundamental for dynamic memory management and system operations.
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 42;
printf("Value: %d\n", *ptr);
free(ptr);
return 0;
}
Output:
Value: 42
Key stdlib.h Functions
malloc()
Allocate memory dynamically
int *arr = malloc(10 * sizeof(int));
free()
Release allocated memory
free(arr);
rand()
Generate random numbers
int num = rand() % 100;
atoi()
Convert string to integer
int num = atoi("123");
🔹 Dynamic Memory Allocation
Dynamic memory allocation allows programs to request memory at runtime using functions from the stdlib.h library. The malloc() function allocates a specified number of bytes and returns a pointer to the allocated memory, while calloc() additionally initializes the memory to zero. When memory needs change, realloc() resizes previously allocated blocks efficiently. For example, int *arr = malloc(10 * sizeof(int)); allocates space for 10 integers on the heap. Always check for NULL return values to detect allocation failures, and remember to call free() when done to prevent memory leaks, which can cause programs to consume increasing amounts of memory over time.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *numbers;
// Allocate memory for 5 integers
numbers = malloc(n * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Fill array with values
for (int i = 0; i < n; i++) {
numbers[i] = i * 10;
printf("numbers[%d] = %d\n", i, numbers[i]);
}
// Free the allocated memory
free(numbers);
return 0;
}
Output:
numbers[0] = 0 numbers[1] = 10 numbers[2] = 20 numbers[3] = 30 numbers[4] = 40
🔹 Random Number Generation
Random number generation in C uses the rand() and srand() functions from the stdlib.h library for generating pseudo-random values. The srand() function initializes the random number generator with a seed value, typically using time(NULL) to ensure different sequences on each program execution. Subsequently, rand() returns pseudo-random integers between 0 and RAND_MAX. For example, int num = rand() % 100; generates a random number between 0 and 99. To create floating-point random numbers or specific ranges, combine rand() with arithmetic operations and type conversions for precise control over the generated values.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed random number generator
srand(time(NULL));
printf("Random numbers:\n");
for (int i = 0; i < 5; i++) {
int random_num = rand() % 100 + 1; // 1-100
printf("%d ", random_num);
}
printf("\n");
return 0;
}
Sample Output:
Random numbers: 42 17 89 3 56