malloc
malloc(n) asks the heap for n bytes and returns a pointer to them, or NULL if it cannot. The bytes are uninitialized. You free them exactly once with free.
Detailed Explanation
<stdlib.h> declares void *malloc(size_t size);. The pointer is aligned for any standard object type. You cast it by assigning to a typed pointer: int *p = malloc(n * sizeof *p);. Using sizeof *p ties the byte count to the pointer's type so a type change cannot silently under-allocate.
malloc(0) is allowed to return NULL or a unique pointer you must still free. Do not dereference it. Treat 0 as a special case if a unique non-NULL pointer would confuse your tables.
Failure is NULL. Ignoring it and writing through the pointer is undefined behavior and, on a quiet day, a crash. On an exciting day it appears to work because the OS overcommitted and the fault arrives later. Check, propagate, clean up.
The contents are garbage. Reading them before writing is undefined. calloc zeros. memset after malloc is an extra pass; use calloc if zero is what you want.
malloc is thread-safe on hosted libcs. It is not async-signal-safe. It can be slow and it can fragment. A tight loop of tiny allocations is a design smell; a pool or an arena is the usual fix.
n * sizeof *p can wrap. If n is attacker-controlled, check n <= (size_t)-1 / sizeof *p before multiplying. A wrapped size is a small allocation and then a buffer overflow.
Pair every success with one free, on every path, including errors after later allocations fail. Ownership should be visible in the function name or the comment: this function allocates, the caller frees.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t n = 3;
int *p = malloc(n * sizeof *p);
if (p == NULL) {
return 1;
}
p[0] = 1;
p[1] = 2;
p[2] = 3;
printf("%d\n", p[2]); /* prints: 3 */
free(p);
return 0;
}#include <stdio.h>
#include <stdlib.h>
static int *dup_ints(const int *src, size_t n)
{
if (n != 0 && n > (size_t)-1 / sizeof(int)) {
return NULL; /* multiply would wrap */
}
int *p = malloc(n * sizeof *p);
if (p == NULL) {
return NULL;
}
for (size_t i = 0; i < n; i++) {
p[i] = src[i];
}
return p;
}
int main(void)
{
int a[] = { 9, 8 };
int *b = dup_ints(a, 2);
if (b == NULL) {
return 1;
}
printf("%d\n", b[1]); /* prints: 8 */
free(b);
return 0;
}Common Gotchas
`malloc` does not zero memory
leftover heap contents are not a secret you should print, and they are not a defined initial value.
Using the pointer without a `NULL` check is undefined behavior
Using the pointer without a `NULL` check is undefined behavior
`malloc(0)` is portable only in the sense that you must `free` whatever you get
`malloc(0)` is portable only in the sense that you must `free` whatever you get and must not dereference it