[LCP]A question regarding malloc and how to check the size of an alloceted memory.

Greg Black gjb at gbch.net
Tue Feb 25 09:10:02 UTC 2003


Kent Nyberg wrote:

| > | I have allocated some memory with malloc.
| > | [...]
| > | Now, i want to check the size of "memory".
| > 
| > You do this by checking the return value from malloc().  If it's
| > NULL, then you got nothing; if it's a valid pointer, then you
| > got what you asked for.
| 
| I know this.

You did not make that clear and your question showed clearly
that your understanding of the malloc() stuff is vague.

| It seems strange that i cant check how big an allocated memory is. But
| hey, i can do without doing it the way i was trying to. So thanks
| anyway.

If you need to know (perhaps because distant functions want to
be careful not to exceed bounds), there are two basic approaches
that you can try:

1. Ensure that you always pass the size of the buffer as well as
   the pointer in function calls.

2. At the time of the allocation, create a small struct with two
   elements -- the size and the pointer; then pass a pointer to
   that struct to all functions.  If you do it this way, you
   might want to wrap malloc() and friends to handle this part
   transparently; or else create your own functions (e.g., with
   names prepended with "x_": x_malloc(), x_free(), etc.) that
   do this for you.

Generally, it's easy enough to track these things; it's just a
matter of giving them some thought.

Greg



More information about the linuxCprogramming mailing list