On 05/05/2017 08:21 AM, Prathamesh Kulkarni wrote:
Hi, I was wondering what constraints apply to function that is annotated with malloc attribute ? For instance is the function allowed to modify global data ?
I'm not familiar with how GCC handles the attribute beyond what I've gathered from experimenting with it and reading the manual but given that the attribute applies to the malloc family of functions which modify global data I'd say the answer must be yes[*].
As far as I understand, from the doc a function could be annotated with malloc attribute if it returns a pointer to a newly allocated memory block (uninitialized or zeroed) and the pointer does not alias any other valid pointer ?
Right. An example helps illustrate it: void* __attribute__ ((alloc_size (1), malloc)) f (int); void* __attribute__ ((alloc_size (1))) g (int); void* foo (int n) { int *p = (int*)f (n); int *q = (int*)f (n); *p = 123; *q = 456; if (*p != 123) // must be false __builtin_abort (); // eliminated return p; } void* bar (int n) { int *p = (int*)g (n); int *q = (int*)g (n); *p = 123; *q = 456; if (*p != 123) // may be true __builtin_abort (); // not eliminated return p; } But a quick search for calls to lookup_attribute with "malloc" as an argument didn't reveal any instances in GCC so I can't say where this happens. Martin [*] This example shows that GCC assumes the function can modify global data. void* __attribute__ ((alloc_size (1), malloc)) f (int); void* foo (int *p, int n) { *p = 123; int *q = (int*)f (n); // f could modify *p *q = 456; if (*p != 123) // may be true __builtin_abort (); // not eliminated return p; }