Good Code
The good version asks the caller to supply the destination buffer and its size. Reviewers can see where the write lands, how overflow is rejected, and how the error path returns.
Lesson 01
Make write ownership visible by receiving caller-owned buffers with size, instead of returning hidden shared storage.
#include <stddef.h>
#include <string.h>
int copy_review_title(char *dst, size_t dst_size, const char *src)
{
// Caller-owned storage makes the write target visible.
if (dst == NULL || src == NULL || dst_size == 0) {
return -1;
}
size_t length = 0;
while (length < dst_size && src[length] != '\0') {
length++;
}
if (length == dst_size) {
return -1;
}
memcpy(dst, src, length + 1);
return 0;
}#include <string.h>
char *copy_review_title(char *src)
{
// Returning shared static storage hides ownership across callers.
static char title[64];
strcpy(title, src);
return title;
}The good version asks the caller to supply the destination buffer and its size. Reviewers can see where the write lands, how overflow is rejected, and how the error path returns.
The bad version returns a pointer to one shared static buffer. Two callers can overwrite each other, and the unchecked strcpy can write past the fixed array.