malloc(size_t size):
size
bytes of uninitialized memory.NULL
.int *ptr = (int*)malloc(10 * sizeof(int)); // Allocates memory for 10 integers
calloc(size_t num, size_t size):
num
elements, each of size
bytes, and initializes all bytes to zero.int *ptr = (int*)calloc(10, sizeof(int)); // Allocates and initializes memory for 10 integers
realloc(void *ptr, size_t size):
ptr
to size
bytes.ptr = (int*)realloc(ptr, 20 * sizeof(int)); // Resizes the memory block to hold 20 integers
free(void *ptr):
malloc
, calloc
, or realloc
.NULL
after freeing.free(ptr); // Frees the allocated memory
ptr = NULL; // Avoids dangling pointers
NULL
: Always check if the returned pointer is NULL
to avoid dereferencing a null pointer.NULL
to avoid accidental access.sizeof
: When allocating memory, use sizeof
to ensure the correct size is allocated, accounting for the data type.malloc
or realloc
to manage arrays that need to change size during runtime.