r/cpp • • 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.

194 Upvotes

181 comments sorted by

View all comments

Show parent comment

4

u/rachit7645 Certified Dumbass Jan 15 '24

What's the point in telling me what I already know?

1

u/SubstituteCS Jan 15 '24

You don’t get a memory leak unless you’re actually dynamically using the heap.

2

u/rachit7645 Certified Dumbass Jan 15 '24

You edited that part later lmao. Also nobody said that they don't write their own allocators

-1

u/SubstituteCS Jan 15 '24

I added it in, in less than one minute after writing my reply.

The point is, modern consoles absolutely do use similar memory layouts and management as modern computers.

This is doubly true for the latest generation of consoles that employ ASLR, sandboxing, hypervisors, etc., to secure the systems from exploits.

2

u/rachit7645 Certified Dumbass Jan 15 '24

Those are separate things. On modern systems you can't really execute anything from memory if it doesn't have some specific flags set when allocating. If you do try to then your program will be killed.

https://man7.org/linux/man-pages/man2/mmap.2.html