0

I'm looking for instructions about documenting exit codes in my C file.

As example, I have the following:

if( !(new_std = (student*) malloc(sizeof(student))) )
    exit(1);

//+1 is for the \0, strlen does not give us that one!
if( !(new_std->name=(char*) malloc(1+sizeof(char)*strlen(name)))){
    free(new_std);
    exit(1);
}

What is the proper way to document in my file, that exit with number 1, means memory allocation failure?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Adiel
  • 1,203
  • 3
  • 18
  • 31

2 Answers2

2

There is no "correct answer", but I would imagine most everyone would suggest using constants: Put these in a common header file that any C file can include.

exit_codes.h

#define EXIT_SUCCESS           0
#define EXIT_GENERAL_FAILURE   1
#define EXIT_OUT_OF_MEM        2

whatever.c

#include "exit_codes.h"
void *p = malloc(100);
if (!p)
    exit(EXIT_OUT_OF_MEM);
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

This is done this way:

typedef enum exit_code {
    SUCCESS = 0,
    ALLOCATION_FAILURE = 1,
    FOO = 2
} exit_code_t;

exit_code_t my_function(void)
{
    //.....
    return ALLOCATION_FAILURE;
}

Using enums for this purpose is better than defines because:

  • You can use switch-case statements over a function returned value and will get warnings if you forget to check for a value.
  • You can print their value using a debugger without adding any special compiler flag.
  • You can use the enum as return-type for functions making it clear what the valid return values are.
Étienne
  • 4,773
  • 2
  • 33
  • 58
  • Thank you. we havn't learned "enum" in the course yet, therefore i'm not allowed to use it, so for now i'll go with define for that matter. Thank you again and have a great week – Adiel Apr 16 '14 at 18:32