r/cpp • u/Knuffya • 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.
24
9
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.
-3
u/Knuffya Jun 16 '21
i was not actually asking if i should not free my memory. it's always nonsensical to leave it hanging around :D
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
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
2
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!
0
u/Jak_from_Venice Jun 17 '21
If you have a “septuple of nested loops” the problem is not using a goto, but a bad design.
Maybe you should split each loop with a method that throws an exception or returns in certain conditions. It’s also cleaner and easier to read.
4
u/phottitor Jun 17 '21
or maybe there is no problem at ll and i can just use a goto.
a problem only arises if you belong to the Church of No goto.
-1
u/Jak_from_Venice Jun 17 '21
If you don’t care to write horrible code and you have not to share with other people, you’re more than welcome.
Since I already had experiences with persons that love this “worst practices”, I try to keep the code I have to work as clean and readable as possible. A set of seven nested loops is not clean, nor readable and the final GoTo is really the icing on the cake.
Also, if you have problems on performances (that I doubt, unless you’re working on magabytes of data that needs parsing in a fraction of seconds), a refactoring of the method is the way to go.
GoTo exists in C to give a single exit points for functions. In C++ are kept for compatibility.
That said: I never said I don’t know how to use it. Jus I don’t like it [cit.]
2
u/Ahajha1177 Jun 17 '21
If you literally have 7 loops, I would argue that's almost certainly a problem.
But some people take it to the extreme and say that even two should be split. On many occasions when writing multiple loops, I would end up making the program even more confusing by splitting it into multiple functions, I might need to pass a whole load of parameters, and I lose context of what I'm doing, as I've now split an algorithm in half where there might not have been a real need to..
I think it depends on the complexity of the inner loops. If it's on the simple side, leave it, unless it could be replaced by an STL algorithm, then use that. If it's really large, then you might want to move it out.
/rant
5
u/ExtraFig6 Jun 17 '21
Gotos are still helpful for things like small state machines
0
u/Jak_from_Venice Jun 17 '21
If you are making a state machine, you should use state objects with enter-exit-run methods.
Meaning of gotos is to provide a common exit for function in C, but in C++ you have exceptions .
Gotos are really a relic from the past and make cose unreadable in C++.
1
u/ExtraFig6 Jun 17 '21
small state machine. In a case where multiple objects would be overkill. If you keep your labels named well and keep the jumps reasonable (state changes) then there's no readability problem.
I learned this from Alex Stepanov. I can find the video lecture if you want. There is also an essay by Knuth called Structured Programming with Gotos that goes over cases where it makes sense to use them. There's plenty bedsides common exit points.
3
Jun 16 '21
Which - what a nice coincidence - you can't use in a kernel.
-2
u/Jak_from_Venice Jun 16 '21
I did’t know C++ is used in the kernel. Maybe on device drivers?
4
Jun 16 '21
Not in Linux. But in other ones.
Afaik Microsoft Windows has parts of the kernel in C++.
Also a lot of smaller, newer Kernels use C++ mainly due to better structuring of code.
3
u/Benjamin1304 Jun 16 '21
I'm pretty sure there's not a single line of C++ in the Linux Kernel knowing what Linus Torvalds thinks about it. But they recently allowed Rust for drivers, so it's not just C anymore
3
Jun 16 '21 edited Jun 16 '21
See http://harmful.cat-v.org/software/c++/linus for the uninitiated.
8
u/helloiamsomeone Jun 17 '21
This email talks so much about nothing in particular. He could've just said that he's been writing C his entire life and that's why git is in C and noone could argue with that, although that much is clearly obvious, so the question was pointless to begin with. Also, if it werks (apparently git works really well), then who cares.
In other words, the only way to do good, efficient, and system-level and portable C++ ends up to limit yourself to all the things that are basically available in C.
Hmm, let me see what Andreas Kling thinks about this:
I originally had some weird idea that kernels should be written in C, so I had tried to write in C, but I thankfully realized very quickly that I was being silly. :^)
3
u/Ahajha1177 Jun 17 '21
His whole argument just comes off as "I hate it because I do". Sure, he says some valid points, like how we tend to rewrite standards relatively quickly (see algorithm vs ranges), and how he needs low level access to just about everything, but everything else is kinda yelling at the wind. And the whole comment about banning it just to piss people off is, well, stupid and immature.
He says he tried it once in 1992. That was before the language was even standardized, much less changed to what it is today. I get that he's used to a single version of a language that is pretty stagnant as is, but that doesn't mean the rest of the world operates like that.
Restricting use? Sure. Barring it outright? I don't see a good reason why.
I'm curious what specifically Rust has over C++ that wooed Linus over. Memory safety? I'm not too well versed on the language, but clearly it's different enough from C++ for him to like it. Wasn't Rust at least loosely based off of C++, at least in some aspects? We see references, RAII, the same namespace syntax, and probably a few other similarities that I don't know about.
I wonder if he would ever say something like "C++ is a bad language with good ideas".
3
u/helloiamsomeone Jun 17 '21
Any kind of association with Rust was/is merely a political move.
If you look at the mailing list, rational people are bringing up valid points against the inclusion of a new language, such as tooling burden for downstream users (where Rust is already a thorn in the side of source-based distros).3
u/AKostur Jun 16 '21
In "the" kernel? There's many kernels around (Linux, Darwin, Windows, etc). And technically, you could use exceptions in a kernel. However, exceptions incur certain overheads that many (most?) kernel developers are unwilling to accept.
7
u/Jak_from_Venice Jun 16 '21
Obviously, when we talk of “The Kernel” we are talking of the OpenBSD’s one
8
2
Jun 16 '21
It isn't even just the overhead.
I think there are some problems with stack-unwinding if you are the kernel...
Furthermore, there's surprisingly little benefit to using them in that context. (Have just gone through writing a small, posix-like-Kernel: I didn't miss exceptions once. I don't know whether that scales to bigger projects, but I think it would.)
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
grepandawk. 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.
1
u/Oo_Tiib Jun 18 '21
The design is used about large problems where we grow whole forests of objects (using things like
std::shared_ptr,std::list,std::set,std::map, lot ofstd::string) to get some little solution. Once we have solution then we do not need that whole forest anymore, but deleting hundreds of millions branches of our forest can be as time consuming as its allocation was.Now as optimization to avoid time consuming delete there are some ways: (1) we can call
exit()as only static and thread-local objects are destroyed byexit()(2) we can refactor it to use likes ofstd::unique_ptr, sortedstd::vector,boost::intrusive::set,boost::graph, lot ofstd::string_view. I prefer that option (2) as those are often cheaper for program to build first and later to release too ... just take bit more attention and living with some inconvenience for programmer.Note that typically only very few kinds of objects (up to 5% of classes used) can reach counts of hundreds of millions in any program and that refactoring is needed only to those few. Rest (95%+) can be lists sets maps strings like these were before as their counts are insignificant.
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
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
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.
-1
u/Jak_from_Venice Jun 16 '21
BOOM! You are freaking right!
Smart-Pointers are definitely a good practice that introduce such a small overhead that is not a problem and the benefits they introduce are great.
Unfortunately I am so deep into legacy code (and compiler) that I forgot I used them continuously in my other projects!
-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
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
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.
3
u/Ahajha1177 Jun 17 '21
This is a fair point. Of course though, it's probably still way easier to destroy a circular dependency with RAII, just break the cycle and it all comes crumbling down.
-2
u/Knuffya 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
unless some specialist adds
shared_ptr_xy = new xy();Not a specialist on smart ptrs, but that should create a leak if i'm not mistaken.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.
Please give an example then how i should use them. If they are actually about equal syntax, i'd switch to them today.
7
u/AKostur Jun 16 '21
unless some specialist adds shared_ptr_xy = new xy();
Can't. Syntax error. One cannot assign a raw pointer to a shared_ptr. (Assuming that shared_ptr_xy is
std::shared_ptr<xy>)Not a specialist on smart ptrs, but that should create a leak if i'm not mistaken.
You're mistaken as that doesn't even compile.
0
u/Knuffya Jun 16 '21
you are right, that does indeed not compile
7
u/AKostur Jun 16 '21
Which makes this a case-in-point. By using smart pointers, it has prevented a bug from even happening in the first place. Were that to be a raw pointer, that line could result in a memory leak (if that raw pointer was really an "owning" pointer, as it loses its current value), or a memory leak later (if the raw pointer wasn't an "owning" pointer and thus won't have delete called on it at some point).
9
u/Wurstinator Jun 16 '21
As another reply suggested, using `auto` is generally a good idea with smart pointers.
`auto ptr = std::make_shared<std::vector<int>>();`
But since you said you don't like `auto` either, to me it seems less like there is any actual reasoning and rather just you not wanting to use modern C++. Which is fine if you are free in your choice (e.g. on single-person projects), you should just be aware that all these "new" features like auto, smart pointers, and many more have been enthusiastically acceppted by the C++ community for good reason.
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.
-5
u/Knuffya Jun 16 '21
auto smart_ptr = std::make_shared(std::vector<uint8_t>{}); auto raw___ptr = new std::vector<uint8_t>();But this is getting silly. 20 characters don't matter. Yes, it's longer with delete. But all in all,,,, using the auto keyword it's fine. But i'm not a fan of that one either :D. But i've found myself using it a few times recently.
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
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
-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.
-5
u/Knuffya 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.
I have never said that i have much experience. That one you made up yourself. I'd rate myself at late-junior-ish.
Did you read the tag? Do you know what a thought experiment is? Have you read that i know that it's bad practice?
Your over reliance on unit tests to figure everything out for you also screams inexperience.
So we should rather not test? Extreme programming, f*ck yeah! That does not sound right to me. Tests should ideally cover everything. Of course this is not possible, so we only test what satisfies a function of risk and time-to-test. But usually memory leaks are super easy to test. Even when it's just for that one module, without specific usecases.
Experienced developers know how much they fuck up and do everything
That's why it's not a bad practice to rely heavily on tests! Ever heard of test driven development?
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.
I have stated multiple times that i make lots of errors and that i am by far no expert. I just catch and fix them.
4
u/TheSuperWig Jun 17 '21
I have never said that i have much experience
You claimed that experienced programmers can use delete correctly. You are using delete. So by your logic you are an experienced programmer.
So we should rather not test?
Where on Earth did they say that? Ironic given the previous quote.
I have stated multiple times that i make lots of errors and that i am by far no expert. I just catch and fix them.
And they're saying tests can't find everything which is why they said you're over reliant on tests.
3
u/Rude-Significance-50 Jun 17 '21
Yeah, I think this one is just gone for now. I'm not going to bother with it any further :p
It's funny, I was going to say that this is the sort of shit I might say when I was just starting. In fact, I think I might have even actually done so. "Why delete stuff if the os just picks it up?" I'm embarrassed to say I think I did. I had a lot of very confused notions...pure dunning kruger going on.
But, you know...reality has a way of instructing young minds just how much they don't know. Some catch on...I hope I did a little but I am an arrogant little fuck.
Turns out that's exactly what is happening here so...cool enough but I got nothing more to add. I was fucking unreachable so...
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.
1
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
7
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
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
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
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
Jun 18 '21
So you're saying that the compiler proper of clang also does not free memory during compilation? Very interesting!
11
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.
3
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
0
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.
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.