8.11.4 Cleanup Variable Attribute

The cleanup (function) attribute indicates the name of a function that the compiler must call when the attributed object goes out of scope. This would be useful to ensure that allocated memory is freed or that an object's contents has been scrubbed before the program proceeds or terminates.

The attribute must be applied only to automatic objects. It must not be used with function parameters or with any objects that have static storage duration. The function argument must be the name of a function; it cannot be a function pointer. The function indicated in the attribute must take one parameter, that being a pointer to a type compatible with the object. The return value of the function (if one is specified) will be ignored.

Where multiple objects in the same scope specify cleanup attributes, their associated cleanup functions are run in the reverse order to that in which the objects were defined (that is, the object defined last in the source will have its cleanup function executed first).

For example, the following shows two automatic objects using the attribute. The functions cleanUp_string() will be called when main() exits and str goes out of scope, then the cleanUp_int() function will be called to process the value held by myVar.
void cleanUp_int(int * dirty) {
  *dirty = 0x55;
}
void cleanUp_string(char ** dirty) {  
  free(* dirty);  
}  

int main(void) {  
  int myVar __attribute__ ((cleanup(cleanUp_int))) = 1;
  char * str __attribute__ ((cleanup(cleanUp_string))) = NULL;
  
  str = (char *)malloc((sizeof(char)) * 100);
  fillCmd(str);
  while (*str++) {
    process(myVar);
  }

  return 0;
}

If the -fexceptions option is in effect, the nominated cleanup function is guaranteed to execute and do soif variables go out of scope during the stack unwinding that happens when processing the exception. Note that the cleanup attribute does not allow the exception to be caught; it only allows an action to be performed. It is undefined what occurs if the function does not return normally.