Search code examples
cexit-code

Documenting exit codes? ( C )


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?


Solution

  • 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);