Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top