17.2.1 Access Function Attribute

The access(access-mode, ref-index[, size-index]) attribute provides additional information about how a function accesses memory. It can assist in diagnosing potential bugs related to memory access via compiler warnings and help the compiler perform better optimizations.

The ref_index argument is the index (starting from the left with index 1) of the function pointer argument that points to the target object being accessed. A function pointer argument can be referenced by at most one distinct access attribute.

The access_mode argument specifies the type of memory access made by the pointer referenced by the ref_index and can be one of:
read_only
The pointer only reads from the target object. Unless the indexed size argument is zero, the target object must be initialized. This check is more robust than just using the const qualifier with the target as it cannot be cast away.
write_only
The pointer (which cannot be to a const-qualified type) only writes to the target object. The object referenced by the pointer need not be initialized.
read_write
The pointer (which cannot be to a const-qualified type) both reads from and writes to the target object. Unless the indexed size argument is zero, the target object must be initialized.
none
The pointer does not access the target object at all. Unless the pointer is NULL, the target object must exist and have at least the size held by the size-index argument. If the size-index argument is omitted for a pointer of void * type, the actual pointer argument is ignored. The referenced object need not be initialized. The mode is intended to be used as a means to help validate the expected object size, for example in functions that call __builtin_object_size.

The optional size_index argument is the index of the function argument that specifies the number of elements of the pointer type referenced by ref-index, or the number of bytes when the pointer type is void *. When this argument is not specified, the pointer argument must be either NULL or point to a space that is suitably aligned and sized for at least one object of the referenced type (this implies that a past-the-end pointer is not a valid argument). The actual size of the access may be less but it must not be more.

For example, the following code uses the access attribute to declare that the pointer argument to puts() will only read its target of unspecified size. The attribute is used again to indicate that the second argument to memcpy() only reads its target and that this target has a size indicated by the value of the third function argument.
__attribute__ ((access (read_only, 1))) int puts(const char *);

__attribute__ ((access (read_only, 2, 3))) void * memcpy(void *, const void *, size_t);