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
andcalloc
.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?