RE: What to do when malloc() returns 0?

Its more than just memory we should think of. There should be a clear idea
of what error conditions have occured.



	E. Support "malloc failed" return code throughout the library
		- requires significant library reengineering
		- error prone
		- requires library clients to do lots of error checking
		+ suitable for use in robust applications


This is what I do with all my code. I use a set of conventions:-

1) Every proceedure is coded as a function returning an integer status code.

2) Every proceedure allocates memory for parameters returned as strings

3) Status return codes are maintained through a catalogue which is updated
	through an AWK script. This will soon be changed to a proper 
	processor.


To make the stuff portable between UNIX and VMS I use macros. Basicaly these
add facilities that should have been in C...


ENTRY_POINT PHB_test (int input, CONST char *input2,
              int &output, char **output2) {

    int 	i;

    BEGIN;

    PRE (PHB_BAD_INPUT, input > 0);
    PRE (PHB_NULL_STRING, input2 != NULL);

    STATUS = PHB_ALLOCATE (char, 32, output2);
    CHECK_STATUS;

    END;
    }


#define BEGIN int _status
#define END return (_status);
#define PRE(x,y) if (y) return x;

At the moment I use a fairly simple minded system where I simply translate
CHECK_STATUS to return (_status); 


But with the same macros you can expand the range quite a bit.  For example 
splice in a label into the END macro. That could then expand to something
that frees all the possible memory elements allocated.

At the moment I use a different scheme whereby all memory is allocated into
a registry which can be freed as a whole. This scheme requires use of a data 
model though.



We could have :-

ENTRY_POINT PHB_test (int input, CONST char *input2,
              int &output, char **output2) {

    int 	i;
    char        *alloc = NULL;

    BEGIN;

    PRE (PHB_BAD_INPUT, ("input"), input > 0);
    PRE (PHB_NULL_STRING, ("input2"), input2 != NULL);

    STATUS = PHB_ALLOCATE (char, 32, &all);
    CHECK_STATUS;

    END ((alloc));
    }


The error condition checking macros now have parameters, these are attached to 
the status return code structure. The end macro calls a proceedure to free
all the elements in the list if the abort status flag is set. Alternatively
it could have two lists, one that is always freed and one that is only freed
if an error occurs.

Henrik has an interesting scheme wherby he attaches all allocated memory to 
structures. The release routine for the structure is responsible for freeing
it.


I think we should in any case define a `public' and a `private' API. Otherwise
there will be no oportunity for other vendors to offer products.



Phill.

Received on Thursday, 21 July 1994 12:30:42 UTC