Example 1 — Copy a string to the heap and free it
The pointer is reset so accidental reuse is caught.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *s = malloc(6);
if (!s) return 1;
strcpy(s, "hello");
printf("%s\n", s);
free(s);
s = NULL;
free(s); /* harmless: free(NULL) does nothing */
printf("freed\n");
return 0;
} How It Works
- Six bytes hold
helloplus the terminator. free(s)releases the block.- A
NULLpointer can be passed tofreeagain without error.
