2

In this answer which discusses about the difference between new and malloc states one difference of new from malloc as Can add a new memory allocator to deal with low memory (set_new_handler).

please give a example of this and how it works?

4

3 回答 3

4

It isn't exactly a new memory allocator, but a function you can register so that it is called when operator new runs out of memory.

If you can then magically fix the out of memory problem, new can try again and see if it works better now. This is most often not very useful, unless your application is holding on to some memory it can release.

于 2012-08-05T15:00:46.053 回答
1

Here's a couple of examples where a new handler might be of use.

  1. Suppose you're on a unix-like machine on which the sysadmin has, for some reason, set a low soft limit on the heap size. The new handler can raise the soft limit to the hard limit and voila! new memory might be available.

  2. Suppose you want your application to hog all the memory, but other already-running applications are in the way. So just make your new handler sleep for a little bit. When one of those already-running programs terminates, viola! new memory is available.

There is at least one commercial application that takes option #2. It is almost always a mistake. Typically the application runs out of memory because a user of the application inadvertently has tried to allocate more memory than exists on any computer. The application will happily munch ever more memory as other running applications quit. Eventually no new programs can be started, including those the operating system needs to run. This application is a rather nice tool for making the machine come crashing to its knees.

于 2012-08-05T15:24:57.603 回答
-1

I think "low memory" is actually indicating "out of memory" in the answer you're linking too. There are plenty of sample code fragments that install an out-of-memory handler by searching on set_new_handler (e.g. http://www.cplusplus.com/reference/std/new/set_new_handler/ )

One implementation I have seen (in production code for a particularly memory-intensive application) used this hook in conjunction with a "rainy-day" block allocation of ~10MB on application startup. If this handler was ever triggered, it would then delete the memory and attempt to enter a "controlled exit" path.

In practice, I found that this wasn't a very effective technique, as behavior once you are out of memory is already unpredictable.

于 2012-08-05T15:06:50.487 回答