开发者

Getting to know size of a reserved memory on the heap

Is there a way to get the size of previously allocated memory on a heap?

For example:

//pseudo-code

void*开发者_如何学Go p = operator new (sizeof(int) * 3);
unsigned size = getSomeHow(p);  


You can't do it at all times, since operator new() can be overloaded in any reasonable way and maybe even without using the runtime heap.

In case operator new() is implemented with malloc() in Visual C++ you can use _msize().


Although Sharptooth is right in his answer (new can be overloaded), the solution might be just in this fact. By overloading new, you can easily add your own implementation of new and delete. In your implementation of new you should:

  • EDIT: round the size to the next multiple of 8 bytes
  • add 8 bytes to the size requested by the application
  • call the systems memory allocate routine (e.g. HeapAlloc in Windows)
  • fill in the originally requested size in the first 8 bytes
  • add 8 to the returned pointer and return this back to the application

The delete operator should do the opposite:

  • subtract 8 bytes from the pointer given by the application
  • call the systems memory deallocate routine

If you do it this way, make sure to implement all flavours of new and delete (throwing and non-throwing, new and new[], delete and delete[], ...).

Also be careful with 3rd party libraries. They sometimes put the call to new in their compiled code in their DLL, but but the call to delete in the header. This means that new and delete will use different implementations and your application will crash.

EDIT:

The rounding to the multiple of 8 bytes and the addition of 8 bytes is needed because data should be stored at an addres that is a multiple of its size:

  • chars can be stored anymore
  • shorts must be stored on an even address
  • longs must be stored on an address that's a multiple of 4
  • doubles must be stored on an address that's a multiple of 8

Since doubles are the largest native data type that I'm aware of, we round to a multiple of 8 bytes and we add 8 bytes to make sure that keep these requirements.


  • You can rewrite the new operator to call malloc() and store the size in a global std::map<void*, size> alloc.

Then this getSomeHow() function will behave like you want:

getSomeHow(void *p){
  return alloc[p]; 
}
  • You can also write your own malloc() and set the loader to use your malloc instead of the standard one. I have done this for tracing purpose, it works fine.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜