With the function attribute malloc, you can instruct the compiler to treat a function as if any non-NULL pointer it returns cannot alias any other valid pointers. This type of function (such as malloc and calloc) has this property, hence the name of the attribute. As with all supported attributes, malloc will be accepted by the compiler without requiring any particular option or language level.
malloc function attribute syntax >>-__attribute__--((--+-malloc-----+--))----------------------->< '-__malloc__-'As with other GCC function attributes, the double underscores on the attribute name are optional.
#include <stdlib.h>
#include <stdio.h>
int a;
void* my_malloc(int size) __attribute__ ((__malloc__))
{
void* p = malloc(size);
if (!p) {
printf("my_malloc: out of memory!\n");
exit(1);
}
return p;
}
int main() {
int* x = &a;
int* p = (int*) my_malloc(sizeof(int));
*x = 0;
*p = 1;
if (*x) printf("This printf statement to be detected as unreachable
and discarded during compilation process\n");
return 0;
}