https://gcc.gnu.org/bugzilla/show_bug.cgi?id=119066
Bug ID: 119066
Summary: Warn when address of local variable is passed to
on_exit
Product: gcc
Version: 15.0
Status: UNCONFIRMED
Keywords: diagnostic
Severity: enhancement
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: redi at gcc dot gnu.org
Blocks: 87403
Target Milestone: ---
A user wanted to report this as a bug:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *ptr;
} sMem;
void call_on_exit(int sts, void *data) {
sMem *m = data;
(void)sts;
printf("In Mem addr: %p, ptr: %p\n", (void *)m, (void *)m->ptr);
}
int main() {
sMem Mem = {.ptr = (char *)0x123456}; /* recognizable value */
on_exit(call_on_exit, &Mem);
printf("Out Mem addr: %p, ptr: %p\n", (void *)&Mem, (void *)Mem.ptr);
return(0); /* substitute 'return' with 'exit' */
}
If the exit handler is invoked because main returned, then the pointer &Mem is
invalid. If the exit handler is invoked because main called exit() explicitly,
then the pointer is valid. The linux man page for on_exit(3) warns about this:
By the time function is executed, stack (auto) variables may
already have gone out of scope. Therefore, arg should not be a
pointer to a stack variable; it may however be a pointer to a heap
variable or a global variable.
GCC could warn when an exit handler is registered on_exit using the address of
an automatic variable, except when a noreturn function is executed before
returning from the function.
On the other hand, it's probably not worth adding special case handling for
this niche misuse of a non-standard SunOS API.
Referenced Bugs:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87403
[Bug 87403] [Meta-bug] Issues that suggest a new warning