1

Let's say I've written a C++ program using Visual Studio and it uses the new operator to allocate memory. I'm wondering whether there is a way that makes new automatically use large pages instead of standard 4KB pages (i.e., without explicit calls to VirtualAlloc by my program).

Thanks for your time.

Salem Derisavi
  • 137
  • 1
  • 10
  • 4
    `new` doesn't even use 4KB pages. It uses `HeapAllocate`. It would be absurd for a `new` of 32 bytes to allocate 4MB of nonpageable memory. If that's what you want, you'll have to do it yourself. – Raymond Chen Apr 22 '13 at 20:53
  • @RaymondChen- Are you *sure* that's what `new` does? Isn't it implementation-dependent? – templatetypedef Apr 22 '13 at 20:59
  • Does Windows or a C++ runtime library (or something like it) manage the heap for the C++ program? My understanding is that the C++ heap manager gets pages (4K or larger) from the OS, and allocates part of it to the user's C++ program. Isn't it so? – Salem Derisavi Apr 22 '13 at 21:05
  • @templatetypedef - the question was about Visual Studio - it is an implementaiton. – user93353 Apr 23 '13 at 00:24
  • Visual Studio comes with C runtime source code. You can read for yourself what `new` does. – Raymond Chen Apr 23 '13 at 04:32
  • @templatetypedef: Did you just ask _the_ Raymond Chen if he is sure about something related to Windows? – rjnilsson Apr 23 '13 at 08:17
  • possible duplicate of [How should I write ISO C++ Standard conformant custom new and delete operators?](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators) – Cody Gray - on strike Apr 24 '13 at 03:32

2 Answers2

3

You can override all new and delete operators. For example

void * operator new(size_t size)
{
    return malloc(size);
}

void operator delete(void * pointer)
{
    free(pointer);
}

As well you should override all variants of this operators:

brainstream
  • 451
  • 4
  • 17
  • Yup, see [here](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators?lq=1) for more information on how to do this the correct way. Naturally, you would want to call `VirtualAlloc` to use large pages. – Cody Gray - on strike Apr 24 '13 at 03:32
1

Implementation specific, once again. All libraries are not restricted to doing that since all the standard says AFAIK is that new allocates memory for C++. For Microsoft's implementation, new always calls HeapAlloc.

http://cboard.cprogramming.com/cplusplus-programming/98364-new-invokes-virtualalloc.html

My understanding is that unless you're running in a virtual machine, the OS has full control over the default heap and stack memory allocation. The above link also brings up a good point in line with Raymond's response to your question: Are you sure you need to use large pages? You open yourself to a good deal of internal fragmentation by doing so.

Nolnoch
  • 103
  • 1
  • 8