Farid Zaripov wrote:
It looks like it is needed to maintain the list of the information
records about allocated blocks for rw_alloc() / rw_free() functions
because munmap() function requires specification of the size of the
freeing block, but rw_free doesn't contains that argument.
Right. The size of the block could be stored in the block itself
along with other bookkeeping data (just like operator_new() in
test/src/new.cpp does it, except hopefully more efficiently):
+---------+---------+---//---+
| address | size | data |
+---------+---------+---//---+
^
|
+--- address
Alternatively, or in addition, it could be stored in a separate
data structure (e.g., a hash table with the address being the key).
Another thing
is the requirement "(e.g., rw_free() shouldn't crash even when passed an
invalid pointer or a valid pointer to a corrupt chunk of memory)" but
http://www.opengroup.org/pubs/online/7908799/xsh/munmap.html page says
"the behavior of munmap() function is unspecified if the mapping was not
established by a call to mmap()".
Correct. The function would have to first check to make sure
the pointer points to a valid block of memory (that's what
__rw_memattr() is for).
If the list of blocks is really needed then is may be useful to add
the checks for memory-leaks and other like checks performed by
operator_new() from new.cpp. But as i understand operator_new() may in
some cases (i.e. some environment variable is set) call rw_alloc()
instead of malloc() and such checks will be performed twice.
That depends on how far we decide to take it. The simplest approach
would be to have the function allocate and safely deallocate memory
without memory leak detection. An enhancement would then be to keep
track of memory leaks.
Maybe maintaining of the list of blocks is unnecessary complication
and it will be enough to add an additional argument size_t nbytes to
rw_free?
What do you think about this?
I think storing the size of the block (probably along with its
address) is necessary if the goal to make it possible to detect
invalid pointers or block corruption and prevent crashes. The
memory leak detection feature would be nice to have but it can
be implemented later on top of the basic functionality.
Martin