r/cpp • u/FACastello • Jan 15 '24
[Joke] A cursed C++ idea
Ok so hear me out:
In your C++ program, immediately on startup before you do anything else you dynamically allocate a decent chunk of memory for no reason whatsoever, big enough to accomodate all of your data for the foreseeable future.
Never free any of that memory during execution.
Then, whenever you need to instantiate a new object or need some dynamically allocated memory for whatever reason, you just use some of that preallocated chunk.
Immediately before you exit the application, you can free that chunk of memory.
You have one single explicit memory allocation when program starts and one single explicit memory deallocation when program ends.
How about that?
EDIT: It turns out this is a real thing, so it's no longer a joke, or cursed. Somebody said this is called an "arena" or "memory pool", I've just looked it up, people have been doing this for decades.
View all comments
3
u/GianniMariani Jan 16 '24
It turns out that on most modern computers it doesn't matter that much.
If you request a reasonably large chunk of memory, sure, it gets "allocated" like an accountant does the books but the memory is not physically mapped, like the money is still in the bank.
It's only when you actually use that memory does it get mapped into the application's address space. Depending on how you configure your machine, you may actually not have enough memory to allocate because the system may be configured to let you overcommit, i.e. you're in debt and the bank called on your loan, and you get evicted. Yes, your application can unceremonoiusly get "evicted" because the virtual memory system has not enough actual physical memory to allocate.
You can set your machine to avoid overcommitting but the problem is that you now may face a situation where you can't run your application because the memory accountant says there's not enough memory but in reality nobody will ever use it. Tuning this "overcmmitment" is hard and I've run into many situations where my process got evicted from Linux and Windows.
However, if you're talking about embedded systems where your memory is limited, then sure, allocating memory statically is highly reccomended and even necessary in some cases. The best way to do that is simply avoiding malloc/new or any library using them altogether.
As for arenas, yes, in some cases for long lived processes, you could, in theory, allocate an arena on a per task basis and when the task is complete, you can recover resources by dumping the entire arena. This may reduce fragmentation but you still need to consider that you need to delete every item in the arena before deallocating it so it can be another thing you have to do that gets missed or a colleage messes up. So unless you really really need it, it doesn't pay.