Coding Style


This document explains some of the coding style used throughout Gateway Anti-Virus. and cshampoo. It is intended to help newbies read the code and give potential contributors an idea about what is expected.

Code Format

We format our source code with GNU indent.

  indent -nbad -nbfda -bap -nbc -br -brs -c33 -cd33 \
  -ncdb -ce -ci4 -cli0 -cp33 -d0 -di1 -nfc1 -nfca   \
  -i8 -ip0 -l240 -lp -npcs -npsl -nsc -nsob -nss    \
  -ts8 -cs -ut *.c *.h

Log file name and line number with every log Message

During initial testing, it became clear that each log message would need to also include its location. For example, here are the log messages we got when testing prior to releasing version 1.0:

  Sep 24 07:55:51 odin gatewayavd[17797]: Virus definitions loaded (155992 signatures).
  Sep 24 07:55:51 odin gatewayavd[17797]: Virus detection engine ready.
  Sep 24 07:55:51 odin gatewayavd[17797]: Socket error (Inappropriate ioctl for device)
  Sep 24 07:55:51 odin gatewayavd[17797]: Server not ready!
  Sep 24 07:55:51 odin gatewayavd[17797]: soap_exit()
  Sep 24 07:56:03 odin gatewayavd[17797]: Exiting...

Which line of code caused the socket error? grep won't find the error because the error message was returned by a library. Unless you're really familiar with the code, you will waste a lot of time hunting down the bug. If you knew what line of code the error message was on, then you could quickly narrow the scope of your search. There are preprocessor macros for the file name and line number, use them. Below is an example usage:

  daemon_log(LOG_INFO, "(%s:%u) Hello, World!", __FILE__, __LINE__);

The only places where file name and line numbers shouldn't be printed are the version and usage output (--version and --help).

Check if malloc() Failed

After each call to malloc(), the pointer should be examined to determine if malloc failed or not. If malloc fails, the function should return.

        char *buffer;

        buffer = (char *) malloc(sizeof(char) * 4096);
        if (!buffer) {
                daemon_log(LOG_ERR, "(%s:%u) malloc() failed!", __FILE__, __LINE__);
                return -1;

Set pointers to NULL after calling free()

Memory should be free()'d inside an if statement. After calling free(), the pointer should be set to NULL.

        if (buffer) {
                buffer = NULL;

Check for NULL struct pointers before Access

        void print_name(struct person *p) {
                if (p && p->name) {
                        printf("Name => '%s'\n", p->name);
                } else {
                        printf("Name => NULL\n");