malloc

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.

The malloc function attribute can be specified inside double parentheses via keyword __attribute__ in a function declaration.
Read syntax diagramSkip visual syntax diagram
malloc function attribute syntax

>>-__attribute__--((--+-malloc-----+--))-----------------------><
                      '-__malloc__-'       

As with other GCC function attributes, the double underscores on the attribute name are optional.
Note:
  • Do not use this function attribute unless you are sure that the pointer returned by a function points to unique storage. Otherwise, optimizations performed might lead to incorrect behavior at run time.
  • If the function does not have a pointer but it is marked with the function attribute malloc, a warning is emitted, and the attribute is ignored.

Example

A simple testcase that should be optimized when attribute malloc is used:
#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;
}