The Swiss-army knife of C. Covers dynamic memory allocation, process control, number conversion, sorting, and pseudo-random numbers.
Include: #include <stdlib.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| malloc | void *malloc(size_t size) | Allocate size bytes; returns NULL on failure |
| calloc | void *calloc(size_t n, size_t size) | Allocate n×size zeroed bytes |
| realloc | void *realloc(void *ptr, size_t size) | Resize a previously allocated block |
| free | void free(void *ptr) | Release allocated memory |
| atoi | int atoi(const char *s) | Convert string to int (no error check) |
| atol | long atol(const char *s) | Convert string to long |
| atof | double atof(const char *s) | Convert string to double |
| strtol | long strtol(const char *s, char **end, int base) | String to long with base & error info |
| strtoul | unsigned long strtoul(const char *s, char **end, int base) | String to unsigned long |
| strtod | double strtod(const char *s, char **end) | String to double with error info |
| rand | int rand(void) | Return pseudo-random int in [0, RAND_MAX] |
| srand | void srand(unsigned int seed) | Seed the pseudo-random number generator |
| abs | int abs(int x) | Absolute value of int |
| labs | long labs(long x) | Absolute value of long |
| qsort | void qsort(void *base, size_t n, size_t sz, int (*cmp)(const void*, const void*)) | Sort array |
| bsearch | void *bsearch(const void *key, const void *base, size_t n, size_t sz, int (*cmp)(const void*, const void*)) | Binary search |
| exit | void exit(int status) | Terminate program with status code |
| abort | void abort(void) | Raise SIGABRT — abnormal termination |
| atexit | int atexit(void (*fn)(void)) | Register function to call on normal exit |
| getenv | char *getenv(const char *name) | Return value of environment variable |
| system | int system(const char *cmd) | Execute shell command (use with caution) |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int cmp_int(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main(void) {
int *arr = malloc(5 * sizeof(int));
if (!arr) { perror("malloc"); return 1; }
srand((unsigned)time(NULL));
for (int i = 0; i < 5; i++) arr[i] = rand() % 100;
printf("Before sort: ");
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
printf("\n");
qsort(arr, 5, sizeof(int), cmp_int);
printf("After sort: ");
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
char *end;
long val = strtol("0xFF", &end, 16);
printf("0xFF = %ld\n", val);
return 0;
}
/* Compile: gcc -Wall -o stdlib_demo stdlib_demo.c */