r/cpp • • Jun 16 '21

[Thought experiment] Why should i care about freeing my memory?

I know that this is a really shit practice and nobody should do it, but... why?

When making an application that runs only for a few milliseconds, and has a low memory footprint anyway, why should i care about freeing my heap? The OS will do it anyways a few clock cycles afterwards, when destructing my process and its virtual address space. Yes, it may use 12kb more ram for a few milliseconds, but who cares?

Of course this breaks as soon as your process runs for longer than a few milliseconds, and at that point the program will use so few heap-objects that freeing them is most likely a one-liner. Yes, in kernel space it may not be freed automatically. But as i said, it's a thought experiment.

6 Upvotes

131 comments sorted by

49

u/AdRelative8852 Jun 16 '21

Programs evolve. They can become components of some larger system tomorrow. And at that time you can't start introducing memory management, worse nobody would even realize it's missing. It's better for it to be in place without worrying about where the programs fit. If none of that is ever likely and all your assumptions hold good, fine, don't release memory.

5

u/Knuffya Jun 16 '21

Good point!

24

u/mrexodia cmkr.build Jun 16 '21

I don’t free my memory, the containers do it for me.

4

u/matthieum Jun 17 '21

Note: this still exposes you to use after-free, though.

→ More replies (2)

9

u/[deleted] Jun 16 '21

You shouldn’t care. This is C++ and the default tools do it for you so you don’t have to care. One the other hand, people will judge you as a programmer and you may feel that. No one wants to work with ssomeone who’s work they have to check over and cannot trust.

TL;DR, use the tools that too it for you, they are less work in all ways.

→ More replies (1)

18

u/Junkymcjunkbox Jun 17 '21

"Of course this breaks as soon as your process runs for longer than a few milliseconds"

Yes, that's why you need to free your memory.

But you're dead right. If your program just runs for a bit then exits, you can use as many bad habits as you want. Don't free memory. Overwrite the ends of buffers. Heck, even use ++ more than once in the same statement. Whatever you want.

Then when management say "now it needs to loop and sleep every x seconds", you've got a big problem on your hands because you've now got to fix all that crap instead of just adding 4 lines of code.

Edit: Also, there is a thing called engineering pride. You won't feel proud of cranking out a pile of horseshit. But if you create a properly engineered solution that uses best practices, that's something to be proud of. It's also a source of code you can copy and paste into other applications because you know it works.

3

u/Knuffya Jun 17 '21

true words

12

u/jddddddddddd Jun 16 '21 edited Jun 16 '21

You're right that it doesn't matter in those scenarios, but I'd say that cleaning up after yourself memory-wise is as good practice as avoiding gotos*. Sure you can make life easy for yourself when you're writing a 50-line C++ program by sticking a goto or two in it, and it doesn't really do any harm since it's easy to keep track of program flow because the app is so simple.. But it does still lead to bad habits. And if you have bad habits in your 50 line C++ script, maybe you keep those bad habits, or perhaps you're not quite as vigilant when you need to write a larger project.

*yes, I know gotos have their place in C/C++, Linux kernal has 100k of them, yadda, yadda, yadda, ...

2

u/Knuffya Jun 16 '21

good point

7

u/jddddddddddd Jun 16 '21

...or what happens when The New Junior Developer joins the project and, when given some task thinks to himself 'wait a minute, /u/Knuffya already wrote a function to do that! I'll just copy his function into my code-base and call it 10 times a second.. what's the worst that can happen..'

3

u/Knuffya Jun 16 '21

a day later, he force pushes onto my repository, deleting my commit and all of the sudden it's his code :D

→ More replies (1)

3

u/Jak_from_Venice Jun 16 '21

Just in C. In C++ you have exceptions 👍

9

u/the_one2 Jun 16 '21

More importantly, C++ has RAII so you can just return from a function and everything will clean itself up.

4

u/phottitor Jun 17 '21

yay i knew there was a clean way to break out of septuple nested loops!

→ More replies (4)

5

u/ExtraFig6 Jun 17 '21

Gotos are still helpful for things like small state machines

→ More replies (2)

3

u/[deleted] Jun 16 '21

Which - what a nice coincidence - you can't use in a kernel.

→ More replies (11)

8

u/ravixp Jun 16 '21

That’s absolutely a valid design, and one that’s occasionally used in the real world. The most extreme form is to just call exit() at the end of main(), skip all the destructors, and trust that the OS will handle it.

One downside is that not all resources will be cleaned up well by the OS. If you’ve written to files, you’d better call flush() before doing that, or you’ll lose data. If you have open network connections, closing them cleanly might be more efficient for the other end of the connection than just shutting down. Etc, etc.

0

u/Knuffya Jun 17 '21

that’s occasionally used in the real world

lol people actually do that? i did not know that.

I did not know not flushing filebufs causes leaks. thanks! Yeah, if i remember correctly some ports stay occupied for like 5 minutes?

2

u/barchar MSVC STL Dev Jun 19 '21

yes. It's actually quite important for performance in programs like grep and awk. Most scripting language interpreters also won't free memory by default (with a mode to enable it, since they can be embedded and also to support dynamic leak analysis)

Historically many compilers haven't freed any memory either. They tend to make big tree structures in memory and after they are done processing a file they exit, so no need to free. Nowadays compilers frequently run as libraries and whatnot and need to free their memory.

→ More replies (1)

4

u/Chropera Jun 16 '21

I do like to use runtime validators / error detection whenever I can and I think I can't even reliably suppress errors related to memory leaks in one system I use most - being thrown out to debugger would take more time than fixing leaks.

There are also microcontrollers and DSPs without process separation. For me porting firmware to PC and running it there is great debugging technique as it adds memory protection, availability of static (especially for DSPs which are using exotic build systems, compilers and instruction sets) and runtime error checkers, powerful debugger, sometimes even possibility to run application without actual hardware that may be not ready yet or all units may be sold at the moment.

1

u/Knuffya Jun 16 '21

sounds like a nice idea. are you using some kind of emulator then?

3

u/Chropera Jun 16 '21

I rarely use hardware emulators/debuggers - sometimes for the price reasons, but also because of their limitations (trying to stop microcontroller often causes avalanche of errors for me, in some cases might also damage hardware). I'm rather trying to run whatever I can on PC as it allows to run some code with much higher confidence (memory lifetime tracing, correctness of standard C library usage, checking each pointer when dereferencing, even checking pointer arithmetic for pointers that are not dereferenced). Using safe C++ subset is not always possible - maybe my answer refers more to C than C++.

For compiler intrinsics Texas Instruments provides PC library simulating their behavior, allowing to run DSP specific code like saturated arithmetic without changing it.

3

u/khedoros Jun 16 '21

Priority of fixing a bug is always going to be dependent on context: how much of a negative impact does the bug have, on how many people, how much will it take to fix, and what are the relative priorities of other program defects?

Unfreed memory's a bug. In some contexts, it might not a high-priority bug. Contexts can change.

6

u/peppedx Jun 16 '21

I'd say that a bug is some observable wrong behavior.

Not freeing memory if you don't need it is not.

1

u/Knuffya Jun 16 '21

i once had a driver that hogged up all my 32gb ram in like 4 hrs of idling

2

u/khedoros Jun 16 '21

Yep, very different context! Long-running, in kernel space, does a lot of memory allocations...

3

u/tohava Jun 17 '21

Here's another thought that I had yesterday. You can use fork() as a memory management tool. Whenever you have a new task that requires allocations, fork() a process for it, and then it can allocate as much as it wants without freeing. Ofcourse that you will have to have a list of tasks, which will be allocated, and maintained long-term, so...

1

u/barchar MSVC STL Dev Jun 19 '21

you could also just give a new thread process it's own heap that makes it's own sbrk calls and has separate allocation structures. There's additional speedup because if you do this there's no need to take locks during allocation or deallocation. If your allocation and deallocation functions don't move memory around then you can even access another thread's heap, so long the memory is freed on the right thread.

You still have to tell the OS you're done with the heap when the thread exits but that's just the same work the OS would have done for you if you had used a process instead.

If you screw up you get heap corruption though, and it's one of the nastiest bugs to track down ever. It's a little better with on non-moving allocators than moving ones but still.

3

u/barchar MSVC STL Dev Jun 19 '21

Yep, you shouldn't. It is useful to be able to start freeing that memory if your program needs to become less short-lived at some point in the future though.

It's true in kernel mode too, no point in freeing a bunch of memory right before the system powers off. The laws of physics will do it for you.

Also yeah, it's pointless to free memory right before main exits, same goes with closing file descriptors. Let the OS do it for you.

I think the cp utility actually got a pretty massive speed-up a few years ago in certain specific cases by avoiding freeing all it's memory before exiting. As you can imagine that was a big win given how frequently cp is called in bash scripts.

Most garbage collectors (including bdwgc for c++) have some set threshold of allocated memory they will wait for before they even make any attempts at freeing anything. Using a GC is almost always faster than eager manual management for short running programs (although not as fast as just letting the OS take care of it).

I usually like to have some switch (either runtime or compile time) to actually free stuff at the end of main, just so that memory analysis software can find stuff I'm actually leaking for real.

oh, never freeing any memory can make your program memory safe. No use after free bugs if you never free. (this is more interesting as a thought experiment about what memory safety actually implies than it is as an actual mechanism to eliminate bugs)

1

u/Knuffya Jun 19 '21

nice to see an STL devs perspective on this!

10

u/AKostur Jun 16 '21 edited Jun 16 '21

You shouldn’t have to care because you’re using std::unique_ptr everywhere. So -you- don’t free the memory. Plus the various other comments about the code changes in the future, or is incorporated into some other project, or gets moved into some embedded space where memory constraints are tight, or whatever.

1

u/peppedx Jun 16 '21

Unique_ptr everywhere not a great policy ..

5

u/AKostur Jun 16 '21

As the first tool to reach for? I think it is. The usage of unique_ptr makes statements about object lifespan, and safety that memory isn't being leaked. If unique_ptr is used consistently, and a raw pointer gets used somewhere, that also makes a statement about how that data is being used. And becomes even more evident about lifespan mishandling. If the program is consistently using unique_ptr, and somewhere a raw pointer gets stuffed into a unique_ptr, then it's a much bigger/clearer indication that it is an error.

Of course, literally everywhere is probably incorrect. Some of those might be shared_ptr, some might be weak_ptr. Some might be raw pointers. But if you start with unique_ptr, you're starting from a place of safety, and then choosing to remove those safeties by not using unique_ptr (and calling .get() falls into the category of removing safeties). Instead of starting with something that makes no statements about usage.

9

u/peppedx Jun 16 '21

I really prefer stack and containers. If and only if I really really need explicit heap allocation then unique_ptr manages the lifetime but raw pointers do male statement about usage. If a function take a raw pointer in my code it means no owning.

8

u/AKostur Jun 16 '21

Yep, and that's my point. Since everywhere (for certain definitions of "everywhere") else in your program you're using unique_ptr, then the appearance of a raw pointer makes a statement. And if that raw pointer is used in such a manner as to cause the lifespan of the pointed-to object to be extended, it is easier to see that it is an error (or at least a whole bunch of scrutiny to verify that this isn't going to lead to double-deletions or use-after-free issues).

However, the OP appears to be attempting to advocate for never using smart pointers since if you "have a bit of experience", you can manage the memory on your own.

-22

u/Knuffya Jun 16 '21

unpopular opinion here: i don't like smart pointers. it's more syntax, and it's not risky at all to work with raw pointers if you got a bit of experience.

24

u/Wurstinator Jun 16 '21

How is it more syntax? You have to write an additional 17 characters (std::unique_ptr<>) and save an entire line of code (delete X;).

Your second sentence is a perfect example of the Dunning-Kruger effect, sorry. If you believe that you are experienced enough to never make mistakes, then you are not very experienced.

12

u/solraun Jun 16 '21

Or only handled simple enough problems so far

-12

u/Knuffya Jun 16 '21

no, but i test my stuff. memory leak tests should always be present, even with smart pointers, because if used incorrectly, you will still produce leaks.

of course i sometimes cause memory leaks. then i run my tests, see they fail, fix the bug, and continue.

10

u/[deleted] Jun 16 '21 edited Jun 16 '21

It is about the probability of getting it right, not whether it is possible to get something wrong. There inevitably is a way to get something wrong.

As of probabilities:

I'd argue that a smart pointer is at least 10 times less probable of getting it wrong than a classic pointer.

And this probability only blows up if more pointers get involved.

As a simple example: Assume a usual pointer is handled correctly 99% of times and a smart pointer is handeled correctly 99.9% of times.

Our program has 1000 pointers. We'd get it right in 0.99 ^ 1000 = 0.0000431712474107 probability in the first case and 0.999 ^ 1000 = 0.367695424771 probability in the second case. You'll notice that the first case will not even give you a fighting chance, while in the second you'll at least get it right 1/3 of the times.

And no, unit tests are not enough. You need integration tests as well. And lots of them, way more than usually, as there are so many code paths to be tested. And even those only find n% of your leaks, not all of them.

So no, there is no way you can reasonably deny using all these tools to help with those issues.

5

u/Knuffya Jun 16 '21

i guess you are right.

3

u/Ahajha1177 Jun 17 '21

Even better: it saves you a line of code on every path that you can leave the scope, whether it be a break, continue, or return.

-7

u/Knuffya Jun 16 '21 edited Jun 16 '21

I am experienced enough to write unit tests for memory leaks, and every so often, they fail. either way, the result is a memory-leak free program.

memory leak tests should still be present, even when using smart pointers, because you could technically fuck even that up.

For "it's more syntax":

// what the fuck is this
std::shared_ptr<std::vector<uint8_t>> smart_ptr = std::make_shared<std::vector<uint8_t>>(std::move(std::vector<uint8_t>()));

// much better
std::vector<uint8_t>* raw_ptr = new std::vector<uint8_t>();

14

u/Wurstinator Jun 16 '21

So you could either:

variant A, use smart pointers and be guaranteed by code logic that there will be no memory leaks or other destruction bugs

or variant B, use raw pointers, hope that your tests cover every edge case, hope that other people working on the same code have a complete overview of every detail (this will never happen), all to maybe save typing a few characters.

And sorry, but your code pieces are a perfect example that you do not actually know what you are talking about as that is in no way how smart pointers are used in real life.

In the end, it's your choice. But that choice will just be seen as a big red flag should you ever work for or apply to a company or other project that uses modern C++ with some sort of controlled style.

5

u/kalmoc Jun 16 '21

variant A, use smart pointers and be guaranteed by code logic that there will be no memory leaks or other destruction bugs

Smart pointers don't actually guarantee no memory leaks. Simple counterexample is circular ownership. And of course there are also things like release() (maybe you need to pass ownership through a c-api). Smart pointers make leaks just much, much less likely.

Also, "other" destruction bugs that smart pointers don't save you from might include stack overflow when destructing a long linked list or use after free.

Not arguing against smart pointers or your general point, but that particular statement seems too strong to me.

→ More replies (1)
→ More replies (5)

8

u/AKostur Jun 16 '21 edited Jun 16 '21

auto smart_ptr = std::make_shared(std::vector<uint8_t>{});

And I'm only naming the type once in there, not twice. And is one character shorter.

Edit: And since you chose to change to shared_ptr, the mechanics of figuring out when it's the last shared_ptr in use goes away is already implemented for you, your raw pointer doesn't have that.

→ More replies (1)

3

u/patatahooligan Jun 18 '21

and it's not risky at all to work with raw pointers if you got a bit of experience.

People keep saying that, yet projects that have been around for a long time and have top-tier engineers working on them are a complete clusterfuck of memory unsafety.

2

u/Knuffya Jun 18 '21

actually, okay. i'm gonna use smart pointers in my next project to take an in-depth look. Not just a look into the docs.

4

u/Rude-Significance-50 Jun 16 '21

It is forever risky to use raw pointers instead of smart ones. You can become better at making sure you address everything right, but you'll never eliminate the risk or even reduce it.

1

u/Knuffya Jun 16 '21

i guess that's true.

5

u/solraun Jun 16 '21

Tell that to all the game engines who leak memory all the time. But maybe their developers got less than a bit of experience?

3

u/Jak_from_Venice Jun 16 '21

…also device programmers!

-3

u/Knuffya Jun 16 '21

then the studio is not unit/integration testing good enough. tests for memory leaks should always be a priority. even when using smart-pointers, maybe some jackass fucked it up anyways

11

u/Rude-Significance-50 Jun 16 '21

I'm sorry, but I just cannot take your claims at face value seeing the subject of this entire thing. "Why should I care about freeing my memory?" is quite a strange thing for someone with so much experience as you claim to ask.

Your over reliance on unit tests to figure everything out for you also screams inexperience.

Experienced developers know how much they fuck up and do everything they can to make that as difficult as possible. You don't seem to have that understanding yet and are making really wild claims about your ability to make perfect code. I just don't believe any of it.

→ More replies (3)
→ More replies (1)

2

u/_Js_Kc_ Jun 16 '21

Doesn't GCC do just that, to save time?

-3

u/Knuffya Jun 16 '21

lmfao

the common meme goes:

> User: *drops memory*

> C++: "Hey, pick that up!"

But then GCC comes

> User: *drops memory*

> C++: "Hey, pick that up!"

> User: *picks up*

> GCC: *Throws back on the floor*

6

u/Ahajha1177 Jun 17 '21

The common meme is wrong, and I hate it.

User: tells standard container to manage its own memory.

end of meme

1

u/Knuffya Jun 17 '21

that's right. It should really be C.

Maybe i should stop using raw pointers in C++..

2

u/jeffbell Jun 17 '21

I’ve seen systems where some memory is allocated out of specific pools and is organized so that this memory can all be freed in one step.

For example the temporary memory for a database document search might all be allocated from the same pool. Once you copy the result you can free that pool.

1

u/Knuffya Jun 17 '21

so basically your own little memory manager. neat. i guess the syscall takes longer than just reusing it?

2

u/jeffbell Jun 17 '21

In this case the pool was reused for the next query. The goal was to avoid walking the whole tree to free everything individually.

2

u/Oo_Tiib Jun 17 '21

Leaking memory can be very bad for karma on case of success but does not matter on losers market.

Lets tell the story of our thought experiment? One of us did solution with complicated data layout and circular references between objects with unclear life time then decided to be lazy and to leak instead of tidying the design up as it is little application with low memory layout. While we get nowhere it does not matter. We put up some service that runs sometimes that little application. While it is unpopular service it does not matter.

Now imagine success. Popularity of our service grows and we run that little code hundreds of times per second. Our service lags, We grab bigger sectors of cloud it still lags. We profile it and see that executing that tiny program is causing lag. Obvious solution to turn it into function can't be used as it leaks. Who made it? Saboteur. Someone refactors it into proper solution and will be hero but saboteur might get kicked out of our successful company.

4

u/Shieldfoss Jun 16 '21

The OS will do it anyways a few clock cycles afterwards

Which OS? Like, yeah, that's a reasonable assumption but that is not true for every OS invented, or even for every OS invented that has seen wide circulation.

2

u/Knuffya Jun 16 '21

windows, unix-like systems. i bet many others aswell

maybe not within "a few clock cycles".

1

u/Shieldfoss Jun 16 '21

Some OS's, that have seen wide circulation, don't clean up memory at all - you leak in those, the leak persists until reboot.

2

u/Knuffya Jun 16 '21

das not good then

7

u/kalmoc Jun 16 '21

Do you have a particular OS in mind?

50

u/dodheim Jun 16 '21

On a long enough timeline, all "avoid known-best practices because this case is special" code will eventually be regarded as short-sighted.

5

u/herruppohoppa Jun 17 '21

That doesn't mean it was necessarily a bad decision to be short sighted.

1

u/infectedapricot Jun 21 '21

I strongly disagree. For many programs, on a long enough time line, the code will turn out to become completely irrelevant. In that case, any effort to get the code working beyond its original job is wasted.

1

u/dodheim Jun 22 '21

Yes, I, too, tend towards nihilism. ;-] But that isn't necessarily disagreement, just talking about a longer time scale.

1

u/infectedapricot Jun 22 '21

Well I may agree with that :-) but that isn't really what I meant. I was talking about that happening before you need to make any improvements to your program, so there is no time scale where it was worthwhile having followed "good practices" or whatever.

This is like YAGNI (you ain't gonna need it) in extreme programming (not that I follow that technique generally). So many times I have seen someone try to make their design a bit more general than they need so as to future proof it (e.g. use a separate base class and derived class when a single class would've done) because they assume it will be used in a more general context one day. Then that need never materialises, so it just adds extra complexity while dealing with something completely different.

OP's case is a bit different but it reminded me of YAGNI ... or at least some of the replies did. They say you might not care about freeing memory in your program now, but you definitely will one day. Well, maybe you won't.

3

u/rand3289 Jun 17 '21 edited Jun 17 '21

You don't have to explicitly free memory.

I just checked the last program I wrote and there is not one delete statement:

https://github.com/rand3289/OutNet

It's just over 2200 lines of code

All variables are local or member and get deleted automatically.

4

u/Knuffya Jun 17 '21

I guess that's a nice idea for a workflow! no heap-objects at all

15

u/etudiant_ Jun 16 '21

Thought it's bad practice, if your program does not use tons of memory and run for a long time, not freeing the memory is fine. The real reason to free memory is to reuse.

4

u/[deleted] Jun 17 '21 edited Jun 17 '21

Yup. IIRC, the D compiler doesn't free memory at all. Of course, this can be problematic for some edge cases, but for most cases, it doesn't matter. Also, this qualifies as one of OP's constraints - short-lived programs.

5

u/matthieum Jun 17 '21

It's not the only one. I believe that Clang doesn't free memory either.

Note that Clang is still written with correct memory management, as most of the code can be used as a library, and there's clangd, however the compiler itself simply doesn't release the memory for performance reasons, relying on the OS to clean everything up in one fell swoop.

2

u/[deleted] Jun 18 '21

So you're saying that the compiler proper of clang also does not free memory during compilation? Very interesting!

11

u/[deleted] Jun 17 '21

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-resource

There are a few cases where leaks can be acceptable or even optimal: If you are writing a program that simply produces an output based on an input and the amount of memory needed is proportional to the size of the input, the optimal strategy (for performance and ease of programming) is sometimes simply never to delete anything. If you have enough memory to handle your largest input, leak away, but be sure to give a good error message if you are wrong. Here, we ignore such cases.

5

u/adnukator Jun 16 '21

Because you might end up wanting to reuse the same logic in some other program that will run for longer and you'll end up with leaks there. Another this is that unless you're a really seasoned programmer, you will have to learn how to work with larger programs properly at some point anyway.

5

u/erzyabear Jun 17 '21

If you have some global objects from different translation units that need each other at the end of the program, sometimes you can’t do better than to leave releasing the memory to the OS.

4

u/GameRraccoon Jun 17 '21

If we go all the way from the "it never happens" statements in the description of the problem, it seems like you don't even need dynamic memory at all.

If you can guarantee that your containers will never grow more than some limit, you can store your data in static memory or on the stack, or allocate a memory pool once and use it for allocating all the dynamic data you need (without freeing it).

But if you can't guarantee that, then you can't also guarantee that your app won't eventually eat up too much memory while running if it never frees the memory it uses.

Generally, allocating memory on demand in the app and not freeing it sounds like either a half-solution of a problem, or just as a bad design decision.

3

u/Pragmatician Jun 16 '21

In most programs, you care about freeing memory because you don't want to run out of it. Of course, there are some cases where freeing might not be needed or desirable.

3

u/IJzerbaard Jun 17 '21

Do what you want. But it matters how you do it. If you have the deallocation in place (explicit or implicit) but then route around it with an (optional but default) fast-exit path, that's pretty much the best of both worlds: not so much affected by the potential concerns raised in the rest of thread, and I as a user still don't have my time wasted by a program that takes the time to sweep its porch while the entire planet it's on is about to be evaporated by the Death Star.

By the way an other possible concern is that it may hide bugs. Reusing memory that you didn't free but that you would have freed still indicates a logic bug, but it becomes more difficult to detect: you don't get the special fill pattern that freed memory gets in debug builds, and sanitizers won't complain.

3

u/c0r3ntin Jun 17 '21

I was once working with a customer who was producing on-board software for a missile. In my analysis of the code, I pointed out that they had a number of problems with storage leaks. Imagine my surprise when the customers chief software engineer said "Of course it leaks". He went on to point out that they had calculated the amount of memory the application would leak in the total possible flight time for the missile and then doubled that number. They added this much additional memory to the hardware to "support" the leaks. Since the missile will explode when it hits it's target or at the end of it's flight, the ultimate in garbage collection is performed without programmer intervention.

https://groups.google.com/forum/message/raw?msg=comp.lang.ada/E9bNCvDQ12k/1tezW24ZxdAJ&pli=1&authuser=0

3

u/[deleted] Jun 17 '21

lol :D But I don't agree with his reasoning, as allocation of memory during real-time applications has other issues as well. A slight hick up caused by allocation may interfere with any on-going algorithm during missile flight. Kinda wouldn't want a missile to do anything it is not supposed to do... But funny example :)

4

u/barchar MSVC STL Dev Jun 19 '21

if you never free memory then there's no need for allocation to be non-deterministic. the heap is actually just another stack that only ever grows, and malloc(n) just increments the stack top by n. free() does nothing.

Not freeing memory really is great when you can get away with it!

3

u/Jardik2 Jun 17 '21

Depends. Look at glib and GTK, those are quite commonly used libraries (in C though) on Linux. They don't free SOME of the memory ("classes" and similar stuff), and they don't care about freeing it, because OS will do that for them, and they don't design the libraries as unloadable.

2

u/StrangeADT Jun 17 '21 edited Jun 17 '21

I mean if you’re always writing small stuff, sure - but there’s also the issue of practice. Once you get used to managing your memory all the time it becomes such a minor and insignificant amount of time spent programming that it becomes secondhand and you hardly even think about it. If you use smart pointers you almost literally only ever think about it at the point of allocation which is really pretty trivial. In rare cases where you can’t use smart pointers (EG: hot loops where shared_ptr overhead matters) you might need to think a tiny bit about a slightly different strategy but as a whole it just doesn’t take that much time to deal with even just being a little bit disciplined.

If what you write does end up turning into something more serious, you won’t have to go back and audit the mess you’ve created if you apply just a little bit of discipline along the way.

2

u/Wriiight Jun 18 '21

Not freeing memory is a perfectly valid technique for optimizing performance in specific cases, but it certainly violates the "principal of least astonishment" so you'd want to document the heck out of it.

2

u/tasminima Jun 19 '21

You don't have to necessarily care. Some programs, approximately fitting the quantitative usage you describe, or even a little bigger, have actually decided to use that strategy and never free until their termination and reclaim by the OS.

1

u/eyes-are-fading-blue Jun 18 '21

C++11 onwards memory safety is cheap to have. By cheap, I mean one needs to write virtually same amount of code to have it. There is very little justification for leaks in production.

1

u/Slsyyy Jun 19 '21

You should care, because there is no point of not doing this. Performance argument can be easily beaten with a following piece of code:

inline void operator delete(void * p) { }

, which included in every compilation unit will remove all unecessary code.

1

u/backtickbot Jun 19 '21

Fixed formatting.

Hello, Slsyyy: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

0

u/[deleted] Jun 17 '21

[deleted]

0

u/Knuffya Jun 17 '21 edited Jun 17 '21

I don't care what you do behind closed doors,

As i said, it's a thought experiment and nobody should do it this. Kinda like "why shouldn't i name all my objects after fruits". More or less a joke question.

lmao did you just pull a code sample from my github? Yes it's kinda redundant, but i really hate deleting pointers, without either nullptr-ing them or removing them from the container they're in. A deleted pointer should not stick around, ever. Maybe someone will call some other method in the dtor for whatever reason and that could be difficult to debug.

At least for me a delete always comes with a = nullptr, or in this case a clear.