Example 1 — A safe string-copy helper
Check the result, copy the terminator, and let the caller free.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Caller must free the returned string. */
static char *copy_string(const char *s) {
size_t n = strlen(s) + 1;
char *p = malloc(n);
if (!p) return NULL;
memcpy(p, s, n);
return p;
}
int main(void) {
char *c = copy_string("codetofun");
if (!c) return 1;
printf("copy: %s (%zu chars)\n", c, strlen(c));
free(c);
c = NULL;
return 0;
} How It Works
strlen(s) + 1includes the terminating null byte.- The function returns
NULLon failure. - The comment documents who owns and frees the result.
