Who frees it? in C
C has no destructors, so ownership lives in the naming and the comments.
#include <stdlib.h>
#include <string.h>
/* Caller owns the result and must call name_free. */
char *name_new(const char *source) {
size_t n = strlen(source);
char *copy = malloc(n + 1);
if (copy == NULL) {
return NULL;
}
memcpy(copy, source, n + 1);
return copy;
}
void name_free(char *name) {
free(name);
}
/* Borrows only: nothing here is freed. */
size_t name_length(const char *name) {
return strlen(name);
}
How it works
- A function whose name creates something returns owned memory.
- A matching destroy function is the other half of the contract.
- Borrowed pointers are
constand never freed by the callee.
Keywords and builtins used here
NULLcharconstifname_freename_lengthname_newreturnsize_tvoid
The run, in numbers
- Lines
- 22
- Characters to type
- 415
- Tokens
- 94
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 56 seconds.
Step 1 of 4 in Ownership & mistakes, step 15 of 25 in Pointers & memory.