Get to know the size of the reserved memory on the heap.

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

//pseudo-code void* p = operator new (sizeof(int) * 3); unsigned size = getSomeHow(p); 
+3
c ++
Nov 01. '10 at
source share
3 answers

You cannot do this always, since operator new() can be overloaded in any reasonable way, and possibly even without using a run-time heap.

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

+8
Nov 01 '10 at
source share

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

  • EDIT: Round the size to the next multiple of 8 bytes.
  • add 8 bytes to the size requested by the application
  • calling a system memory allocation program (for example, HeapAlloc on Windows)
  • enter the originally requested size in the first 8 bytes
  • add 8 to the returned pointer and return it back to the application

The delete statement should do the opposite:

  • subtract 8 bytes from the pointer specified by the application
  • call the procedure for freeing system memory

If you do this like this, make sure that all the options new and deleted are implemented (throwing and not throwing, new and new [], deleting and deleting [], ...).

Also be careful with third-party libraries. Sometimes they put a call to their compiled code in their DLL, but the call to delete is in the header. This means that the new and the remote will use different implementations and your application will crash.

EDIT:

You need to round to a multiple of 8 bytes and add 8 bytes, because the data must be stored in addres, which is a multiple of its size:

  • characters can be saved more
  • shorts should be kept at an even address
  • longs must be stored at an address that is a multiple of 4
  • doubles must be stored at an address multiple of 8

Since doubles are the largest native data type that I know of, we have rounded to a multiple of 8 bytes, and we add 8 bytes to ensure that these requirements are met.

+5
Nov 01 '10 at 10:30
source share
  • You can rewrite the new operator to call malloc() and save the size in the global std::map<void*, size> alloc .

Then this getSomeHow() function will behave the way you want:

 getSomeHow(void *p){ return alloc[p]; } 
  • You can also write your own malloc () and install the bootloader to use your malloc instead of the standard one. I did this to track the target, it works great.
+1
Nov 01 '10 at 10:30
source share



All Articles