peter.slizik peter.slizik - 21 days ago 5
C Question

GCC: __attribute__((malloc))

Quoting from GCC documentation (emphasis mine):


The malloc attribute is used to tell the compiler that a function may
be treated as if any non-NULL pointer it returns cannot alias any
other pointer valid when the function returns and that the memory has
undefined content
. This often improves optimization. Standard
functions with this property include
malloc
and
calloc
.
realloc
-like
functions do not have this property as the memory pointed to does not
have undefined content.


I have the following code:

struct buffer {
size_t alloc; // Allocated memory in bytes
size_t size; // Actual data size in bytes
char data[]; // Flexible array member
};


#define ARRAY_SIZE <initial_value>

buffer *buffer_new(void) __attribute__((malloc))
{
struct buffer *ret;

ret = malloc(sizeof(struct buffer) + ARRAY_SIZE);
if (!ret)
fatal(E_OUT_OF_MEMORY);

ret->alloc = ARRAY_SIZE;
ret->size = 0;

return ret;
}


Now I'm a bit puzzled here: though I didn't initialize the
data
member, I still set the
alloc
and
size
fields to their respective values. Can I still consider this allocated segment to be of "undefined content" and use the malloc attribute?

Answer

It is safe to mark your buffer_new function with __attribute__((malloc)), because the block it returns contains no pointers.

The latest GCC documentation clarifies the meaning of __attribute__((malloc)): the block returned by a function so marked must not contain any pointers to other objects. The intention is to help the compiler estimate which pointers might possibly point into the same object: the attribute tells GCC it needn't worry that the object your function returns might include pointers to something else it's tracking.