Memory
Ownership
An ownership convention decides which function is responsible for freeing heap storage.
Ownership
ownership.c
#include <stdio.h>
#include <stdlib.h>
int *makeValue(int value) {
int *ptr = (int *)malloc(sizeof(int));
if (ptr != 0) {
*ptr = value;
}
return ptr;
}
int consumeValue(int *owned) {
int result = *owned;
free(owned);
return result;
}
int main(void) {
int value = ;
int *owned = makeValue(value);
if (owned == 0) {
return 1;
}
int result = consumeValue(owned);
owned = 0;
printf("result=%d owned=%d\n", result, owned == 0);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int *makeValue(int value) {
int *ptr = (int *)malloc(sizeof(int));
if (ptr != 0) {
*ptr = value;
}
return ptr;
}
int consumeValue(int *owned) {
int result = *owned;
free(owned);
return result;
}
int main(void) {
int value = ;
int *owned = makeValue(value);
if (owned == 0) {
return 1;
}
int result = consumeValue(owned);
owned = 0;
printf("result=%d owned=%d\n", result, owned == 0);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int *makeValue(int value) {
int *ptr = (int *)malloc(sizeof(int));
if (ptr != 0) {
*ptr = value;
}
return ptr;
}
int consumeValue(int *owned) {
int result = *owned;
free(owned);
return result;
}
int main(void) {
int value = ;
int *owned = makeValue(value);
if (owned == 0) {
return 1;
}
int result = consumeValue(owned);
owned = 0;
printf("result=%d owned=%d\n", result, owned == 0);
return 0;
}
owner
The owner of a heap pointer is responsible for calling `free`.
transfer
Passing a pointer to a consuming function can transfer that responsibility.