Contents

4. Usage of my_malloc and my_free

Try to avoid using malloc and realloc as much as possible and use new and zap(delete). But sometimes you may need to use the "C" style memory allocations in "C++". Use the functions my_malloc() , my_realloc() and my_free(). These functions do proper allocations and initialisations and try to prevent memory problems. Also these functions (in DEBUG mode) can keep track of memory allocated and print total memory usage before and after the program is run. This tells you if there are any memory leaks.

The my_malloc and my_realloc is defined as below. See Appendix C my_malloc.cpp. and the header file Appendix D my_malloc.h.


// size_t is type-defed unsigned long
void *local_my_malloc(size_t size, char fname[], int lineno) 
{
        size_t  tmpii = size + SAFE_MEM;
        void *aa = NULL;
        aa = (void *) malloc(tmpii);
        if (aa == NULL)
                raise_error_exit(MALLOC, VOID_TYPE, fname, lineno);
        memset(aa, 0, tmpii);
        call_check(aa, tmpii, fname, lineno);
        return aa;
}

// size_t is type-defed unsigned long
char *local_my_realloc(char *aa, size_t size, char fname[], int lineno)
{
        remove_ptr(aa, fname, lineno);
        size_t  tmpii = sizeof (char) * size + SAFE_MEM;
        aa = (char *) realloc(aa, tmpii);
        if (aa == NULL)
                raise_error_exit(REALLOC, CHAR_TYPE, fname, lineno);
        // do not memset here!!! memset(aa, 0, tmpii);
        aa[tmpii-1] = 0; // set last location to 0
        call_check(aa, tmpii, fname, lineno);
        return aa;
}

An example on usage of my_malloc and my_free as below:
        char    *aa;
        int             *bb;
        float   *cc;
        aa = (char *) my_malloc(sizeof(char)* 214);
        bb = (int *) my_malloc(sizeof(int) * 10);
        cc = (float *) my_malloc(sizeof(int) * 20);

        aa = my_realloc(aa, sizeof(char) * 34);
        bb = my_realloc(bb, sizeof(int) * 14);
        cc = my_realloc(cc, sizeof(float) * 10);

Note that in my_realloc you do not need to cast the datatype as the variable itself is passed and correct my_realloc is called which returns the proper datatype pointer. The my_realloc has overloaded functions for char*, int* and float*.
Contents