When programming in C, distinguishing between pointers that point to stack memory and those that point to heap memory is of vital importance (e.g. one cannot call free
with a reference to stack-allocated memory). Despite this, the C language itself provides no base facilities to qualify pointers to make the aforementioned distinction explicit.
Are there any programming patterns in which people use an empty macro definition called heap
(i.e. #define heap
) or something similar for use as a pointer qualifier?
The utiltiy of such a definition becomes obvious when looking at the type signatures of the functions in the following (admittedly contrived) example:
int *stack_add(int *a, const int *b)
{
*a += *b;
return a;
}
int *heap heap_add(const int *a, const int *b)
{
int *heap sum = malloc(sizeof *sum);
if (sum == NULL) {
return NULL;
}
*sum = *a + *b;
return sum;
}
Despite the usefulness of such an idiom, I cannot recall ever having seen this before.