Is it possible to free memory using an offset pointer?
Let's say I have an allocation in memory containing a string, "ABCDEFG"
, but I only have a pointer to the 'E'
. Is it possible, on win32, to free that block, given a pointer that is within the block, but not at the开发者_StackOverflow社区 start? Any allocation method would work, but a Heap*
function would be the path of least resistance.
If not a native solution, have there been any custom memory managers written which offer this feature?
EDIT: This isn't an excuse to be sloppy. I'm developing an automatic memory management system using 100% compile-time metadata. This odd requirement seems to be the only thing standing in the way of getting it working, and even then it's needed only for data types based on arrays (which are slicable).
It would be possible for the memory allocation routines in the runtime library to check a given memory address against the beginning and end of every allocated block. That search accomplished, it would be easy to release the block from the beginning.
Even with clever algorithms behind it, this would incur some kind of search with each memory deallocation. And why? Just to support erroneous programs too stupid to keep track of the beginning of the blocks of memory they allocated?
The standard C idiom thrives on treating blocks of allocated memory like arrays. The pointer returned from *alloc is a pointer to the beginning of an array, and the pointer can be used with subscripts to access any element of that array, subscripts starting at 0. This has worked well enough for 40 years that I can't think of a sensible reason to introduce a change here.
I suppose if you know what the malloc()
guard blocks look like, you could write a function that backs up from the pointer you pass it until it finds a 'best guess' of the original memory address and then calls free()
. Why not just keep a copy of the base pointer around?
If you use VirtualAlloc
to allocate memory, you can use VirtualQuery
to figure out which block a pointer belongs to. Once you have the base address, you can pass this to VirtualFree
to free the entire block.
精彩评论