Re: memory allocation wrapper



"goose" <lkman@xxxxxxxxxxxxx> wrote in message
Hello all

I've written a wrapper for malloc and friends. Its
available from

http://www.lelanthran.com/downloads/os_mem/index.php

The reason for doing writing this so that newbies
can finally get answers to the following
newbie questions:
1. How do I know how much memory a pointer points to?
2. How can I tell if a pointer is valid?

I know most of the regs don't need this, but be
a good samaritan and point out the bugs :-)

Comments and criticisms(sp?) welcome; note that it aims
for c99 compliance only.

goose,

There's a much easier way of achieveing what you want to do.
Simply put a structure at the start of the allocated memory, add your
control information, and return the pointer immediately after.
Then when the user calls the free, subtract the size of the control
structure, and free. Similarly for the access functions.

There is a niggly snag. malloc() must return memory aligned for any purpose.
In practise you can get "good enough" portability by padding your structure
out to an even number of doubles. In standards land, you risk the horrors of
UB, and there is no way of achieving a fully compliant program in ANSI C.

--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.


.



Relevant Pages

  • Re: sizeof(ptr) = ?
    ... The value returned by malloc() is of type 'void*', ... The memory is typeless until an object has been written ... Since 'void' is defined to be an incomplete ... an lvalue of a complete type, there must be a pointer conversion ...
    (comp.lang.c)
  • Re: Checking validity of a file pointer
    ... because the pointer looks valid. ... detected (preferably by having fclose return an error indication ... if the buffer of the file is returned from the malloc() function, ... with memory returned from mallocfunction in that buff ...
    (comp.lang.c)
  • Re: 2D array of structures
    ... Don't cast the return value of malloc(), ... you allocate here memory for 7 such structures. ... a pointer to the start of this memory, which is of type 'STRUCTURE *' ...
    (comp.lang.c)
  • Re: malloc does not return null when out of memory
    ... >> malloc() when the overcommitted memory is touched, ... >> touched it and there's no actual memory there. ... This patch does ... > 1) mallocreturning a pointer, and then sometime later the program dies ...
    (freebsd-stable)
  • Re: Difference between Macro and Function...
    ... > | Look up the library documentation; malloc is used to request memory space ... using a pointer to freemakes sense. ... that share a single region of memory. ...
    (comp.lang.c)