[comp.lang.c++] Small Model Malloc

postnews@geyer.UUCP (Postnews) (04/09/91)

Hi, folks.

We are having a little trouble with a problem I don't dare calling a bug.
Using a malloc()-call in small model with a variable size produces bizzare
results, if the requested memory size is not an unsigned value. For example

  cp = (char*)malloc(70000);

does not return NULL as you might expect, but reserves about 4500 bytes
of memory and returns a pointer to this area. Obviously the value is
casted to unsigned implicitly. We are now looking for an elegant(!) way
to produce proper results, for example replacing the malloc-routine in
CS.LIB (module NearHeap). If anybody out there has already solved this
problem, please E-mail me.
Solutions for C are not needed (we managed that), but only such for
C++ (TC++ 1.01).

Thanx, a lot
                           Joscho

PLEASE do not reply to the address in the FROM: line, but to

  SCHOOF@SUNNY.INFORMATIK.UNI-WUERZBURG.DBP.DE

Andreas.Kaiser@p0.f7014.n244.z2.FidoNet.stgt.sub.org (Andreas Kaiser) (04/10/91)

 P>   cp = (char*)malloc(70000);

 P> does not return NULL as you might expect, but reserves about 4500
 P> bytes of memory and returns a pointer to this area. Obviously the
 P> value is casted to unsigned implicitly. We are now looking for an
 P> elegant(!) way to produce proper results, for example replacing the
 P> malloc-routine in CS.LIB (module NearHeap).

A good compiler (or lint, for C) should complain about a truncated constant, when the function is declared as malloc(unsigned) and sizeof(unsigned) < sizeof(70000).

You cannot replace malloc() in the library by a version with a larger argument, since some other library functions will still call it with only an unsigned provided as argument. You can however replace calloc() with a version using long multiplication to evaluate the gross size and return NULL if it is too large. But calloc(70000,1) will still yield a bad result.

A possible solution is to use
        #define malloc(n) large_malloc((long)(n))
where large_malloc is defined as
        char *
        large_malloc(n)
            long n;
        {
            if ((unsigned)(n+4) != n)
              return NULL;
            return malloc((unsigned)n);
        }

The reason for the (n+4) is that some compilers return garbage when
called with malloc(65535).

      Andreas

 * Origin: kaiser@ananke.stgt.sub.org - Stuttgart, FRG (2:244/7014.0)