On Mon, Apr 1, 2019 at 12:20 AM Sami Kerola <kerolasa@xxxxxx> wrote: > > Hello, > > The http://man7.org/linux/man-pages/man3/on_exit.3.html tells: > > The on_exit() function registers the given function to be called at > normal process termination, whether via exit(3) or via return from > the program's main(). > > When I compile and run the following code return from main() does > not seem to do what manual page is telling. Is this a bug in manual > or in glibc? > > $ cat test.c > #include <stdio.h> > #include <stdlib.h> > > struct data { > int argc; > char *argv; > }; > > static void run_on_exit(int exit_val __attribute__((__unused__)), void *arg) > { > const struct data *ctl = (struct data *)arg; > > printf("on_exit: %d & %s\n", ctl->argc, ctl->argv); > } > > int main(int argc, char **argv) > { > struct data ctl = { > .argc = argc, > .argv = argv[0] > }; > > printf("argc: %d & %s\n", ctl.argc, ctl.argv); > on_exit(run_on_exit, &ctl); > > if (1 < argc) > exit(0); > return 0; > } > > $ ./a.out foobar > argc: 2 & ./a.out > on_exit: 2 & ./a.out > > $ ./a.out > argc: 1 & ./a.out > on_exit: -168651984 & (null) This is UB, since the ctl variable no longer exists at the time of run_on_exit execution, as run_on_exit is called outside of the scope of the main() function. The fact that it is called within main()'s scope in the first case (when exit() is called explicitly) is just a coincidence and an implementation-specific detail. Note also, that on_exit is non-standard and atexit() should be used instead. -- Eugene Syromyatnikov mailto:evgsyr@xxxxxxxxx xmpp:esyr@jabber.{ru|org}