CKTIS / C
malloc — C23 memory-allocation function
`malloc(size)` from `<stdlib.h>` reserves space for an object of `size` bytes and returns a pointer to the start of a disjoint region, or a null pointer on failure. The new bytes have an indeterminate representation; unlike `calloc`, the function does not clear them.
Version: C23
Syntax
void *malloc(size_t size);malloc(size) from <stdlib.h> reserves space for an object of size bytes and returns a pointer to the start of a disjoint region, or a null pointer on failure. The new bytes have an indeterminate representation; unlike calloc, the function does not clear them.
The example allocates an array of five int, checks the result, stores squares, sums the now-initialized elements, and prints 1 25 55 before calling free exactly once. It demonstrates a complete ownership cycle rather than merely printing an address.
Before malloc(count * sizeof *p), exclude size_t multiplication overflow, for example with count <= SIZE_MAX / sizeof *p. For size == 0, C23 leaves it implementation-defined whether null or a distinct pointer that must not be used to access an object is returned. A successful result is aligned for types with fundamental alignment and the required size; read only after writing, and end ownership with one matching free.
Examples
#include <stdio.h>
#include <stdlib.h>
int main(void){int *values=malloc(5*sizeof *values);if(!values)return 1;int sum=0;for(int i=0;i<5;i++){values[i]=(i+1)*(i+1);sum+=values[i];}printf("%d %d %d\n",values[0],values[4],sum);free(values);return 0;}
Result
1 25 55
The example allocates an array of five `int`, checks the result, stores squares, sums the now-initialized elements, and prints `1 25 55` before calling `free` exactly once. It demonstrates a complete ownership cycle rather than merely printing an address.