On Sat Jan 28 11:39:19 2023 +0000, Jinoh Kang wrote:
The [GCC document][1] states:
Using the attribute with no arguments is designed to improve
optimization by relying on the aliasing property it implies. Functions like malloc and calloc have this property because they return a pointer to uninitialized or zeroed-out, newly obtained storage. However, functions like realloc do not have this property, as they may return pointers to storage containing pointers to existing objects. Additionally, since all such functions are assumed to return null only infrequently, callers can be optimized based on that assumption. However, it goes on give an example that goes like this:
int fclose (FILE*); int pclose (FILE*); __attribute__ ((malloc, malloc (fclose, 1))) FILE* fdopen (int, const char*); __attribute__ ((malloc, malloc (fclose, 1))) FILE* fopen (const char*, const char*); __attribute__ ((malloc, malloc (fclose, 1))) FILE* fmemopen(void *, size_t, const char *); __attribute__ ((malloc, malloc (pclose, 1))) FILE* popen (const char*, const char*); __attribute__ ((malloc, malloc (fclose, 1))) FILE* tmpfile (void);
Notice that `FILE` is internally known to contain valid pointers. Maybe it merely meant that `realloc` returns pointers that aliases with existing pointers instead? [1]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
Reading through the GCC bug report titled "documentation for attribute malloc contradicts itself",[1] which ended in a change to the documentation, it's clear that not only must the returned pointer be unique, but also it may not point to valid pointers either. There was a substantial amount of argument over whether such a strict requirement was a good idea.
My guess is that it's OK to use the malloc attribute on functions that return FILE* because you're not allowed to dereference a FILE pointer, so the compiler never even considers whether it points to valid pointers. Internally, I don't think glibc calls one of those functions and dereferences the result either. Please let me know if you find a counterexample.