Jow Forums doesn't know C++

>tfw Jow Forums can't figure out why this code is a memory leak waiting to happen

class Foo {
int *a;
int *b;
public:
Foo() {
a = new int();
b = new int();
}
~Foo() {
delete a;
delete b;
}
};


You aren't a brainlet, are you user?

Attached: images.jpg (300x168, 6K)

Other urls found in this thread:

en.wikipedia.org/wiki/Rule_of_three_(C++_programming)
stackoverflow.com/questions/24879746/memory-leak-in-class-constructor-of-c
sqlite.org/testing.html
twitter.com/AnonBabble

It deletes the pointer not the memory allocated?

nope

Dangling pointers

It uses the wrong language.

nope

>Jow Forums can't do my homework for me

Public: should be in the header not the cpp file

Why the fuck are you using pointers to integers where plain integers would work fine?

Default copy and moves. Will cause a leak

The compiler probably changes it to this anyway

I already know the answer, hence the reason I am able to definitively tell people whether they have produced the correct answer.

Unfortunately Jow Forums is a terrible place to do this, as anybody can pretend to be you

It's called an example, user. You see, typically when programmers discuss such matters, they create an artificial example which consists of the minimum amount of code to reproduce the issue.

>no copy contructor
>no assignment operator

en.wikipedia.org/wiki/Rule_of_three_(C++_programming)

That's not the answer

"new b" can throw
But who the fuck cares

Winner. Take this cookie. Now, do you know how to solve this problem?

Attached: 1371607143890.jpg (616x462, 20K)

Use smart pointers with make_unique/make_shared, that's like their entire justification.

>GC languages are bad
>Can't define a basic class without defining 3 (THREE) functions, or deal with memory leaks and UB
>In 2018

Yes it is.

Foo *bar = new Foo();
Foo *baz = new Foo(*bar);
delete bar;
// go on... try to delete baz

If you don't catch the throw the program will just crash, not memory leak

And if you do catch the throw, you will be unable to call the destructor on the object and the memory allocated for int *a will never be freed.

Unless you tell your throw to just kill the program, which is a sensible option because your program probably can't reasonably continue without the variable that's trying to be allocated

Use a vector instead of a pointer, dumbass. Also drop the destructor. Go back to your homework.

Brainlet here. Why does that happen?

stackoverflow.com/questions/24879746/memory-leak-in-class-constructor-of-c

If the constructor fails, you cannot call the destructor.

this, op is a fucking retard who saw this fucking example in a c++ book and now pretends to "know" c++. what a NEET cuck.

class Foo {
int *a;
int *b;
public:
Foo() : a(0), b(0) {
try {
}
catch(std::bad_alloc &exc) {
if (a != 0) delete a;
if (b != 0) delete b;
}
}
// blah blah do your copy constructor and assignment operator here
~Foo() {
delete a;
delete b;
}
};

lmfao this is such a non-existent issue in your example that it's not even funny - if your allocator doesn't have space to allocate 8 bytes of memory then you have much more to worry about than fucking destructors

>Read book about C++
>HURRR YOU DON'T """"""""KNOW"""""""" C++ LIKE ME BOI ;)

You can catch the throw within the constructor and clear out a if b fails.

If you can't allocate a few bytes of memory, then you're running out of memory anyways. Catching the error would do no good. Might as well just reset the computer.

Or, you know, you could just use a vector, like a sane person.

class Foo {
vector vals;
public:
Foo(): vals(2) {}
int get_a(int a){return vals[0];}
int set_a(int a){return vals[0]=a;}
int get_b(...
}


This gives the added bonus that you get an additional level of abstraction. You can, for example, now use the wrapper functions to log any access to your variables.

>being this retarded
You clearly don't understand what the fundamental problem is and you are trying to specific a specific minimal example instead of seeing how that issue applies to the larger picture and solving that problem.

You are making a lot of assumptions here. First of all, as has already been stated (and as should be blatantly fucking obvious), this is just a minimal example of the problem. In the real world, it's not always going to be just a simple int pointer.

Well, that changes the fucking problem.

Anything written in C++ is a memory leak waiting to happen. Why aren't you using rust

Not it doesn't. The same problem of memory leaking is present in both cases. Nobody designs a full real-world application to show off a simple issue. Don't pretend to be that retarded, user.

>tfw 30yo boomer can't learn new tricks

maybe you should have at least allocated a bigger array of ints you stupid second-year uni ape

How could making a new int fail...?

run out of ram

As another user mentioned, the program won't be able to reasonably continue anyway. It would just crash very quickly. It doesn't matter how how simple or complicated the scenario is. Catching the error would be pointless, because you won't even have enough memory to do error handling.

Error handling requires no heap retard

So it makes a, throws while making b, and if you catch it, you have no way to get rid of a?

Correct. The destructor cannot be called because the object was never instantiated.

Huh.

You have to think about a LOT of stuff that isn't business logic when you write C++. Seems hard.

>You have to think about a LOT of stuff that isn't business logic when you write C++. Seems hard.
As other people have pointed out, you can avoid this issue by using smart pointers, which is what everyone learning C++ should be doing since that concept was introduced in the 2011 standard. It's considered bad practice to use raw pointers these days, because programmers are notoriously bad at avoiding memory leaks.

>But who the fuck cares
Going to elaborate, since I thought my post would be the end of this shitty thread. All modern OS's overcommit, which means you won't ever get bad_alloc. And if you say "but what if I am working in memory-constrained environment?", then you shouldn't be using standard allocators anyway.

That depends on the how the compiler/interpreter handles it, cunt face. It doesn't even matter, because you won't have enough memory to do any meaningful error handling.

Handle all the errors you want, you can't do fuck all if you can't create the variables you need or any later ones in the program

But you can't assume you'll always be working on modern codebases, right? In my career so far, I'd say 70% of what I've worked on was maintaining old projects.

And how many of them had issues with being unable to malloc due to being out of ram without the program catastrophically failing in a hundred other ways?

what the fuck do you expect to happen then, the program keeps trying to allocate until ram is available? jesus fuck, show me a language in which your programs don't exit when you run out of virtual memory

I'm agreeing with you, my point is this "issue" is completely useless

-fno-exceptions

What the fuck is your problem? Did someone shoved a brick up your ass?

I mean, I'd guess that the example OP gave is to point out that you should catch stuff in your constructor and deallocate for a safe landing, not just OOM errors...

It depends on the program. It may be possible that the construction of a particular object is not critical to operation of the program. It could also be that the program only has to wait and try again. Rather than having it continue to leak memory every time it tries to instantiate an object in such a condition, it is better to gracefully recover from error.

You really don't have much imagination if you can't think of any time a program can continue running after failing to allocate memory.

No copy constructor and assignment operator.

You're a fucking retard.

No it doesn't, you retard

>falling for the meme language

But you probably wouldn't have allocated the object to begin with if your program didn't need it, so you're SOL either way if you don't have enough memory. Thus this is a stupid provision.

Failing to allocate b does not free a.
There, do I get a cockie?

Here, this is the ONLY way to solve this problem.
PROVE me wrong.
OP, that'll be $10 for the tutoring session.

Attached: Untitled.png (525x591, 15K)

Wouldn't nothrow stop bad_alloc from throwing?

Delete this before OP sees it for fucks sakes.

You can just do it without std::nothrow right

Not your personal tech support. Stop trying to help OP.

It will make the pointers null if it fails allocating memory.

Just use regular fucking variables. The whole reason objects exist at all is so we don't have to fuck around with pointers.

class Foo {
int *a;
int *b;
public:
Foo() {
if(!new int() || !new int()){ // if we can't allocate two integers
delete a;
delete b;}
else {
a = new int();
b = new int();
}
}
~Foo() {
delete a;
delete b;
}
};

Why would you check nullpointers, you made them null already and you can safely delete nullptr.

>Or, you know, you could just use a vector, like a sane person.

Jesus fucking christ are you stupid? You just clicked that stackoverflow link and copied-pasted the first answer even though it doesn't apply well in this situation.


Well, at least we know you are a real developer.

Not true at all. I could be allocating some manner of object to serve an HTTP request. If I fail to create it, say I'm out of memory, disk space, temporary connectivity issues to the backing DB, whatever, then I should return a 500.

I should continue running, though. It's the upstream load balancer's job to realise I've spewing nothing but 500s (if I am), and back the load off, killing and replacing my server if the problem continues.

Not sure about that guy, but there is a variation to OP's problem that actually does involve nulling the pointers. Consider this modified version of what OP posted and ignore the rule of five for the sake of this example:
class Foo {
A *a;
A *b;
public:
Foo(int x, int y) : a(nullptr), b(nullptr) {
a = new A(a);
b = new A(b);
}
~Foo() {
delete b;
delete a;
}
};


There are two viable solutions to this problem. One is to use smart pointers in the constructor. In that case, it wouldn't even be necessary to define a constructor at all. The other way is to use delegating constructors. Consider the following:
class Foo {
A *a;
A *b;
public:
Foo() : a(nullptr), b(nullptr)
Foo(int x, int y) : Foo() {
a = new A(x);
b = new A(y);
}
~Foo() {
delete b;
delete a;
}
};


Because of the delegating constructor, the destructor can still deallocate memory even if b = new A(y); fails. As long as at least one constructor runs successfully, the destructor can also run.

or you could just use malloc lol

sqlite.org/testing.html

>SQLite, like all SQL database engines, makes extensive use of malloc() (See the separate report on dynamic memory allocation in SQLite for additional detail.) On servers and workstations, malloc() never fails in practice and so correct handling of out-of-memory (OOM) errors is not particularly important. But on embedded devices, OOM errors are frighteningly common and since SQLite is frequently used on embedded devices, it is important that SQLite be able to gracefully handle OOM errors.

OOM testing is accomplished by simulating OOM errors. SQLite allows an application to substitute an alternative malloc() implementation using the sqlite3_config(SQLITE_CONFIG_MALLOC,...) interface. The TCL and TH3 test harnesses are both capable of inserting a modified version of malloc() that can be rigged to fail after a certain number of allocations. These instrumented mallocs can be set to fail only once and then start working again, or to continue failing after the first failure. OOM tests are done in a loop. On the first iteration of the loop, the instrumented malloc is rigged to fail on the first allocation. Then some SQLite operation is carried out and checks are done to make sure SQLite handled the OOM error correctly. Then the time-to-failure counter on the instrumented malloc is increased by one and the test is repeated. The loop continues until the entire operation runs to completion without ever encountering a simulated OOM failure. Tests like this are run twice, once with the instrumented malloc set to fail only once, and again with the instrumented malloc set to fail continuously after the first failure.

Attached: .jpg (1920x1080, 229K)

What that's insane. Can I make the default ctor private and use it delegated?

You've combined 2 separate potential solutions to make a program that will eventually segfault instead of leak.

>In that case, it wouldn't even be necessary to define a constructor at all
Meant to say destructor.

I'm not sure. Try it out. Seems like it should work, but I've never tried.

Jesus christ stop ruining a good ruse.
Pukka! 100% perfectly valid

Attached: Untitled.png (332x362, 7K)

good shit go౦ԁ sHit thats some goodshit rightthere rightthere if i do ƽaү so my self i say so thats what im talking about right there right there (chorus: ʳᶦᵍʰᵗ ᵗʰᵉʳᵉ) mMMMMᎷM HO0OଠOOOOOOଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ Good shitsauce me the FUCK up cheesy shit cheesy sHit thats some cheesyshit rightth ere rightthere if i doƽaү somy self i say so thats what im talking about right there right there (chorus: ʳᶦᵍʰᵗ ᵗʰᵉʳᵉ) mMMMMᎷM HO0OଠOOOOOOଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ Cheesy shit euphoric logic !euphoric loGic thats some euphoric logic rightthere Carl Saganif i do ƽaү so gentlemen i say so thats euPhoric logic right there Richard Dawkins (chorus: socrates died for this shit) mMMMMᎷM HO0OଠOOOOOOଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ euphoric logic slam me the FUCK uP john cena JOhN cEna john cena johncena johncena johncena u can't see me if I do ƽaү so my self i say so thats what im talking about right there right there (chorus: ʳᶦᵍʰᵗ ᵗʰᵉʳᵉ) mMMMMᎷM HO0OଠOOOOOOଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ John ceNa POTENTIALLY sign me the FUCK up average shit modera̷̶te sHit thats some ALright shit right th ere right

allocation can fail throwing an exception without cleaning up.
huuuurrr duuuuuur
Other than that, there's no memory leak unless you don't properly destruct Foo, in which case that's just your own retardation.

#include

class Foo {
std::unique_ptr a;
std::unique_ptr b;

public:
Foo() : a(std::make_unique()), b(std::make_unique()) {}
Foo(const Foo &other) : a(new int(*other.a)), b(new int(*other.b)) {}
Foo(Foo &&other) noexcept : a(std::move(other.a)) {}
Foo &operator=(const Foo &other) {
a = std::make_unique(*other.a);
return *this;
}
Foo &operator=(Foo &&other) noexcept {
a = std::move(other.a);
return *this;
}
~Foo() = default;
};

wow modern C++ so elegant

Not him, but how could a constructor like this possibly fail?

out of memory

Most of that shit is completely unnecessary. You don't understand the rule of 5. Back to wikipedia.

It can't, OOM handling is a thing from the 70s when mainframes had 2MB of RAM. Modern operating systems have virtual memory/swap/paging so either your program gets sacrificed for memory or granted some from a magical chest.

>All modern OS's overcommit
you can still run out of virtual address space. The kernel can't do anything about that but return an error code. Since swapping out any of it would definitely be an error. (I am NOT talking about swapping physical pages. I mean swapping virtual pages).

And how would this constructor failing because you're out of memory possibly cause a memory leak when there is not even any memory left

this problem in this example seems like a complete nonissue

b = new int();
if this throws you dunn goof'd

It's pretty obvious by your ignorance that you have never worked with production servers in a business environment.

there could be enough memory for a and not for b
now imagine it's some massive thing instead of an int

I have actually I write enterprise java.
Because for as long as your program is running, it's hogging resources.

>has never had to deal with oom and heap fragmentation hell

I c

i'm sorry user but you're retarded. the problem will be the same.