The Daemon Pattern

This is a common pattern seen in daemons (in C like languages).

int some_func()
{
     struct foo_s *foo = (struct foo_s *) malloc(sizeof(struct foo_s));
     ...
     while (1) {
          ...
          bar(foo);
          ...
     }

     free(foo);
     return r;
}
pacman
 Courtsey: pacman.wikia.com

The unreachable free() makes no sense. A missing free(), though unreachable, annoys a purist. Considering the scope and visibility of foo(), putting it on the heap is not the best approach. The scope is within some_func(), and the visibility is until the process exits (killed).

Another approach is to make foo global.

static struct foo_s *foo;

int some_func()
{
     foo = (struct foo_s *) malloc(sizeof(struct foo_s));
     ...
     while (1) {
          ...
          bar(foo);
          ...
     }

     free(foo);
     return r;
}

But here the scope of foo is all throughout the program, and so is the visibility. Precisely, same reason why global variables are considered bad, especially, if multiple threads are accessing one.

A better approach is to have the scope of foo limited to the function, and the visibility all throughout where the reference is passed.

int some_func()
{
     static struct foo_s foo;
     ...
     while (1) {
          ...
          bar(&foo);
          ...
     }

     free(foo);
     return r;
}

The static local variable puts it on .bss and so no stack hogging. Making foo local limits the scope while the visibility is passed on with the reference.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s