Double free() or corruption:C++ - c++

Why if I write a code like this (X is a generic class) calling constructor and destructor
int main()
{
X one ();
one.~X();
return 0;
}
give me this error?
Double free() or corruption:C++

You should almost never call destructors explicitly, they are called implicitly when an object falls out of scope (or deleted, if allocated on heap). First you manually deallocate background's array by calling background.~Y(), and next this same array tries to get deallocated once more at the next }.

Calling the destructor of an object is almost always wrong. Actually I never came across a situation where this was right. You need to read about RAII and maybe this example will help you to understand why you get the error:
#include <iostream>
struct Foo{
Foo() { std::cout << " constructor " << std::endl; }
~Foo() { std::cout << " destructor " << std::endl; }
};
int main(){
Foo foo;
// foo.~Foo(); // <- never ever do this !
} // <- object is destroyed here !
Run this and you will see, that the destructor is called already. Destroying an already destroyed object leads to the error you get.

Related

C++ destructor order of member with shared_ptr

If class A contains class B, then when A destruct, B's destructor will be called first, i.e., the reversed order of their nested relationship.
But what if A contains a shared_ptr of B, while B contains a raw pointer to A, how should we handle the destructor to make it safe?
Considering the following example:
#include <iostream>
#include <memory>
#include <unistd.h>
struct B;
struct A {
int i = 1;
std::shared_ptr<B> b;
A() : b(std::make_shared<B>(this)) {}
~A() {
b = nullptr;
std::cout << "A destruct done" << std::endl;
}
};
struct B {
A *a;
B(A *aa) : a(aa) {}
~B() {
usleep(2000000);
std::cout << "value in A: " << a->i << std::endl;
std::cout << "B destruct done" << std::endl;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
{
A a;
}
std::cout << "done\n";
return 0;
}
You can see in A's destructor, I explicitly set b to nullptr, which will trigger B's destructor immediately, and blocking until it finish.
The output will be:
Hello, World!
value in A: 1
B destruct done
A destruct done
done
but if I comment out that line
~A() {
// b = nullptr; // <---
std::cout << "A destruct done" << std::endl;
}
The output will be:
Hello, World!
A destruct done
value in A: 1
B destruct done
done
it seems that A's destructor finished without waiting B to destruct. But in this case, I expected segment fault, since when A already destructed, B tried to access the member of A, which is invalid. But why the program doesn't produce segment fault? Does it happen to be OK (i.e., undefined behavior)?
Also, when I change
{
A a;
}
to
A * a = new A();
delete a;
the output is still the same, no segment fault.
It is important to be precise about what is happening. When A is destroyed, the following events happen in the following order:
A::~A() is called.
The A object's lifetime ends. The object still exists, but is no longer within its lifetime. ([basic.life]/1.3)
The body of A::~A() is executed.
A::~A() implicitly calls the destructors of direct non-static members of A in reverse declaration order ([class.dtor]/9, [class.base.init]/13.3)
A::~A() returns.
The A object ceases to exist ([class.dtor]/16). The memory that it used to occupy becomes "allocated storage" ([basic.life]/6) until it is deallocated.
(All references are to the C++17 standard).
In the second version of the destructor:
~A() {
std::cout << "A destruct done" << std::endl;
}
after the statement is printed, the member b is destroyed, which causes the owned B object to be destroyed. At that point, i has not yet been destroyed, so it is safe to access it. After that, the B destructor returns. Then, i is "destroyed" (see CWG 2256 for some subtleties). Finally, the destructor of A returns. At that point, it would no longer be legal to attempt to access the member i.
B has a pointer to A, but doesn't deallocate the memory of it (e.g. no delete). So The pointer is removed but not the memory allocated, which is all fine.
Basically, the pointer is on the stack and it contains the address of some (assumed) allocated memory on the heap. Yes it get removed from the stack, but the allocated memory remains. That's what delete is for. To remove the allocated memory on the heap. However in your case, you don't want that memory to be removed and your pointer is what we call a non-owning pointer. It points to something, but it's not responsible about the cleanup (actually B doesn't own the memory that the pointer is pointing to).
Just wanted to point out that your comment is incorrect:
~A() {
std::cout << "A destruct done" << std::endl;
}
A destructor is DONE when you get out of the curly braces. You can see that in a debugger, doing step-by-step. That is where b will be deleted.
If class A contains class B, then when A destruct, B's destructor will be called first, i.e., the reversed order of their nested relationship.
No. If you destroy an object of type A, that calls the destructor of A, so that is called first.
However, call to B's destructor will finish first: The destructor of A begins by executing the destructor body, and then proceeds to destroy the sub objects. The destructor body finishes first, then the sub object destructors, and finally the destructor of A will be complete.
But what if A contains a shared_ptr of B, while B contains a raw pointer to A, how should we handle the destructor to make it safe?
In the destructor body of A, make the pointed B point somewhere else other than the object that is being destroyed:
~A() {
b->a = nullptr;
}
If you point it to null such as in my shown example, then you must also make sure that B can handle the situation that B::a may be null i.e. check before accessing through the pointer.
it seems that A's destructor finished without waiting B to destruct.
That's not what we observe. The body of the destructor of A has finished, but the destructor does not finish until the member destructors finish first.

Destructor not working in C++ for anonymous object?

My friend told me C++ allows us to call a member function even if the instance is destroyed from memory. So I write the code below to verify it, but why the value of a can be extracted even after the object was destroyed? I thought there would be a segment fault.
#include <iostream>
class Foo{
public:
Foo(int a = 0){
std::cout << "created" << std::endl;
this->a = a;
}
~Foo(){
std::cout << "destroyed" << std::endl;
}
Foo *f(){
std::cout << "a=" << a << std::endl;
return this;
}
private:
int a;
};
Foo *iwanttocallf(int i){
return ((Foo)i).f();
}
int main(){
for(int i = 0; i < 3; i++)
iwanttocallf(i)->f();
}
Output from my Macbook Air:
created
a=0
destroyed
a=0
created
a=1
destroyed
a=1
created
a=2
destroyed
a=2
Usually compilers are implementing the member function call as a call to a regular c function with the first argument a pointer to the object (gcc does it like that as far as I know). Now if your pointer is pointing to one destroyed object it doesn't mean that the memory where the a has been stored will be changed, it might be changed. So it is undefined behavior in general. In your case you got a value of a but maybe next time with a different compiler or different code you will crash. Try to use placement new operator then set a value of 'a' = 0 in destructor... and follow the memory where the object is stored.
"My friend told me C++ allows us to call a member function even if the member is destroyed from memory"?
I don't know what your friend is trying to say. But you call member function on some object of a class
unless it's a static member. So, if you delete that object from memory, how could you call any function of that class on that object. It's an undefined behavior.
This is covered in §12.7 [class.cdtor]:
[..] For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor
finishes execution results in undefined behavior.
As other people have told, this involves undefined behavior, and any result is possible. I'll try to explain why you encountered this particular result (stuff working normally).
Objects in C++ are represented by contents of memory. When an object is destroyed, its
destructor is executed, but the memory still contains the previous value. The output operation outputs the value taken from memory (which is now "free" - doesn't belong to any object) - if there is not much stuff going on between the destructor call and the output, the old value will remain.
However, if you change your code to add some calculations, the bug will be evident. For example, I added the following function that simulates some calculations:
int do_stuff()
{
int result = 0;
int x[3] = {0};
for (auto& n: x)
{
n = rand();
result ^= n;
}
return result;
}
I also added a call to this function:
Foo *f(){
std::cout << "foo1: a=" << a << std::endl;
do_stuff();
std::cout << "foo2: a=" << a << std::endl;
return this;
}
I got the output:
foo1: a=0
foo2: a=424238335
This clearly shows that it's not safe to expect anything consistent when dealing with deleted objects.
By the way, some debuggers overwrite the memory that deleted objects occupied with a special value like 0xcdcdcdcd - to make some sense out of this kind of unpredictable behavior. If you execute your code under such a debugger, you will see garbage printed, and will immediately know that your code is buggy.

c++ destroy an object on stack frame

I try to understand what happen when an object destroy on stack.
here is my sample code:
#include <stdio.h>
struct B {
~B() {puts("BBBB");}
};
int main()
{
B b;
b.~B();
}
output is
BBBB
BBBB
based on the output, I can tell the object is destroy twice.one is ~B(), another one is after "}". how and why can a object get destroy twice?
update:
after i review replies, I think the destructor doesnt destroy this object. it there a way to destroy an object before it reach out of scope "}".
Thanks
You are not supposed to invoke the destructor by hand. What's happening is you are invoking the destructor and then when the object gets popped off the stack the destructor is called again automatically by the compiler.
~B() is called before the destruction
Destructors are usually used to deallocate memory and do other cleanup
for a class object and its class members when the object is destroyed.
A destructor is called for a class object when that object passes out
of scope or is explicitly deleted.
Source
So you are just calling a function twice.
There's minimal-to-no garbage collection in C++, objects are simply destroyed when they go out of scope. So you could replace your test to this:
#include <iostream>
struct B {
B() { std::cout << "B()" << std::endl; }
~B() { std::cout << "~B()" << std::endl; }
};
int main()
{
std::cout << "start main" << std::endl;
{ // scope
std::cout << "start scope" << std::endl;
B b;
std::cout << "end scope" << std::endl;
} // <-- b gets destroyed here.
std::cout << "end main" << std::endl;
}
If you want an object on the stack over which you have control over the lifetime of, you can do something like this:
#include <iostream>
#include <memory.h>
struct B {
B() { std::cout << "B()" << std::endl; }
~B() { std::cout << "~B()" << std::endl; }
};
int main()
{
std::cout << "start main" << std::endl;
{ // scope
std::cout << "start scope" << std::endl;
void* stackStorage = alloca(sizeof(B));
std::cout << "alloca'd" << std::endl;
// use "in-place new" to construct an instance of B
// at the address pointed to by stackStorage.
B* b = new (stackStorage) B();
std::cout << "ctord" << std::endl;
b->~B(); // <-- we're responsible for dtoring this object.
std::cout << "end scope" << std::endl;
} // <-- b gets destroyed here, but it's just a pointer.
std::cout << "end main" << std::endl;
}
Live demo: http://ideone.com/ziNjkd
Remember, though, it's the stack. When it goes out of scope, it goes away - if you don't destroy it, it just dissapears.
{
void* stackStorage = alloca(sizeof(B));
B* b = new (stackStorage) B(); // "in-place new"
} // (*b)s memory is released but (*b) was not dtord.
The only time you would manually call a destructor is when you've got grounds to use placement new
Keep in mind that the destructor is like any other function. The only difference with other function is that it is automatically called when the object is deallocated. You cann see this like an event. You get a chance to clean everything before the object get annihilated. Calling the destructor by hand does not deallocate the object.
Object construction/destruction in C++ follows this simple rule:
Anything automatically allocated (and constructed) is automatically destructed.
Anything explicitely allocated with new is explicitely destructed via delete.
Anything explicitely constructed with new() must be explicitely destructed by calling the destructor.
The destructor has to be called in all three cases, the difference is in how the memory for the object is allocated:
The object is on the stack, its allocation is managed by the compiler.
The object is on the heap, its allocation is managed by the programmer.
The object is anywhere, construction and destruction is independent of allocation.
In the first two cases, we have a combination of allocation and construction, and consequently a combination of destruction and deallocation. The third case is entirely different, but fully supported by the language, and the reason that you are allowed to explicitely call a destructor; because in this case an object is constructed without allocating memory for it. Consequently, it must be destructible without deallocating memory as well. This case can be used like this:
void* buffer = (void*)new char[sizeof(Foo)]; //allocation
Foo* myFoo = new(buffer) Foo(); //construction
myFoo->~Foo(); //destruction
Foo* anotherFoo = new(buffer) Foo(); //reuse the buffer to construct another object in it
anotherFoo->~Foo(); //destruction of the second object
delete buffer; //deallocation
Note, that this actually constructs two objects, one after the other in the same place, destructing them explicitely before the memory is reused. The buffer could also be a large slap of memory to store many objects, std::vector<> works like this.
So, yes, destruction does destroy your object, you must not use it after destruction. But since you used an automatically allocated and constructed object in your question, the compiler also took care of destructing it, leading to the double destruction. This is always a bug, objects must never be destructed twice, but the language allows you to do it anyway.
What you are doing is a pretty good example of a variable running out of scope.
int main()
{
//Main is started
B b;
/* What happens is that `b` is constructed as a local
variable and put on the runtime stack.*/
b.~B();
/*You then invoke the destructor manually which is bad practice.
But it is possible and it will execute the code.
However, the state of the resulting instance is undefined.*/
}
/*Main ends and local variables defined in the
current scope get destroyed. Which also means that B's destructor
is called the second time */
FYI - the only time you are supposed to do manual destruction of an object is when it is put on the heap like this:
// create an instance of B on the heap
B* b = new B();
// remove instance and implicitly call b's destructor.
delete b;
i would like to answer my own question.
after a lot of reading, Here is my summary.
1. destructor doesnt destroy it's object. the object stays at stack
until out of scope.
2. nothing can destroy a stack object.
3. the destructor did destroy RESOURCE inside the object.
sample code:
struct B {
B() {happy="today is a good day"; hour = 7;}
~B() {puts("BBBB");}
std::string happy;
int hour;
};
int main()
{
B b;
std::cout << b.happy << b.hour <<std::endl;
b.~B();
std::cout << b.happy << b.hour <<std::endl;
}
output:
today is a good day7
BBBB
7
BBBB
we can see a resource b.happy is gone after b.~B() is called. this is a proof of my point 3.
you see the b.hour(int type is not a resource) is still here. this is a proof of my point 1.

Confused about C++ memory deallocation

So in C++ if I create an object useing new I should always deallocate it using delete
For example
Segment::Segment(float length)
{
segmentLength = length;
angle = 0.0f;
x = Rand::randFloat(1.0f, 1.5f);
y = Rand::randFloat(1.0f, 1.5f);
vx = Rand::randFloat(0.0f, 1.0f);
vy = Rand::randFloat(0.0f, 1.0f);
prevX = Rand::randFloat(0.0f, 1.0f);
prevX = Rand::randFloat(0.0f, 1.0f);
};
And lets say I use it like this in another class such as,
this._segmentObject = Segment(2.0f);
this._segmentPointer = new Segment(2.0f);
In the destructor of that class, I know I should call delete on the this._segmentPointer, however how do I make sure memory is deallocated for the other one?
however how do I make sure memory is deallocated for the other one?
It is automatically. This is why this type of storage is called automatic. Automatic storage is released at the end of the storage’s life cycle, and the objects’ destructors called.
The object life-cycle ends when the program control leaves the scope where the object has been allocated.
Things not allocated with new, new[] or the malloc family should be destructed and "freed" when the object goes out of scope.
Often this simply means that that the code has reached the end of the block it was declared it or that the object that it was in was destructed (one way or another).
To see this in action, you can do something like this:
struct C {
C() { std::cout << "C()" << std::endl; }
~C() { std::cout << "~C()" << std::endl; }
};
struct B {
B() { std::cout << "B()" << std::endl; }
~B() { std::cout << "~B()" << std::endl; }
private:
C c_;
};
struct A {
A() { std::cout << "A()" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
int main() {
B *b = new B; // prints "B()", also constructs the member c_ printing "C()"
{ // starts a new block
A a; // prints "A()";
} // end of block and a's scope, prints "~A()"
delete b; // prints "~B()", also destructs member c_, printing "~C()"
}
Note: that if we did not do delete b, the "~B()" and "~C()" would never print. Likewise, if c_ were a pointer allocated with new, it would need to be delete'd in order to print "~C()"
The memory for this._segmentObject is part of the memory of the containing object, and will be released when the containing object is destroyed.
this._segmentObject is assigned from a temporary object that is created on the stack and deleted when it goes out of scope.
Not only that, You should only allocate with new and deallocate with delete in Constructors or Destructors, otherwise your program can leak if an exception is thrown.
The destructors for all class-type member objects are called at the time of the destruction of the primary class. So your this object, which is allocated on the stack, will have it's destructor called when it goes out-of-scope. At that time, any class-type member objects of your this object will have their own destructors called in addition to the destructor for your this object which will call delete on the member pointer.
For instance, take the following code sample:
#include <iostream>
using namespace std;
class A
{
public:
A() {}
~A() { cout << "Destructor for class A called" << endl; }
};
class B
{
private:
A a;
public:
B() {}
~B() { cout << "Destructor for class B called" << endl; }
};
int main()
{
B b;
return 0;
}
When run, the output becomes the following:
Destructor for class B called
Destructor for class A called
So you can see that when b, which is allocated on the stack, goes out-of-scope at the end of main, the destrutor for class B is called, which in-turn, after executing the body of the destructor function, calls the destructors for any of its class-type member data objects, which in this case would mean the destructor for class A. Therefore in your case, the pointer would have delete called on it in the destructor for your this class, and then the destructor for _segmentObject would be called after the destructor for this had completed execution of the body of its destructor. Then once all the destructors for the non-static data-member objects had been called, the destructor for this then returns.
The _segmentObject is allocated automatically on the stack.
The object destructor will be called automatically when the variable gets out of scope.
As others have said, you don't need to explicitly do anything to reclaim the memory used by this._segmentObject. As soon as it goes out of scope, the memory will be reclaimed.
It's not clear why you would use Segment in both ways. You should try to ensure you use the Resource Acquisition Is Initialization idiom, as it removes much of the need for checking new / delete pairs. That is, just use the this._segmentObject version, not the pointer.
Your application may not allow it, though.

Meaning of "~" (tilde) symbol in C++?

// AirlineTicket.h
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int getNumberOfMiles();
private:
int mNumberOfMiles;
};
I want now what is the meaning of ~AirlineTicket(); in this code?
I don't know the meaning of ~ (tilde).
It is the destructor.
It gets called when you destroy (reaching end of scope, or calling delete to a pointer to) the instance of the object.
In the context you're using it, it defines a destructor.
In other context such as the following one, it's also called bitwise negation (complement):
int a = ~100;
int b = ~a;
Output: (ideone)
-101
100
~ signs that it is a destructor and when ever the object goes out of scope, corresponding destructor is called.
When the destructor is called ?
Taking an example -
#include <iostream>
class foo
{
public:
void checkDestructorCall() ;
~foo();
};
void foo::checkDestructorCall()
{
foo objOne; // objOne goes out of scope because of being a locally created object upon return of checkDestructorCall
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
}
int main()
{
foo obj; // obj goes of scope upon return of main
obj.checkDestructorCall();
return 0;
}
Results on my system:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
This example just serves to indicate when a destructor is called. But destructor is written only when the class manages resources.
When class manages resources?
#include <iostream>
class foo
{
int *ptr;
public:
foo() ; // Constructor
~foo() ;
};
foo:: foo()
{
ptr = new int ; // ptr is managing resources.
// This assignment can be modified to take place in initializer lists too.
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
delete ptr ; // Returning back the resources acquired from the free store.
// If this isn't done, program gives memory leaks.
}
int main()
{
foo *obj = new foo;
// obj is pointing to resources acquired from free store. Or the object it is pointing to lies on heap. So, we need to explicitly call delete on the pointer object.
delete obj ; // Calls the ~foo
return 0;
}
Results on my system:
Destructor called 0x9b68008
And in the program, you posted I don't see a need to write destructor. Hope it helps !
It's the class destructor. You might want to pick up an introductory text on C++ development, as destructors are a fundamental concept in OOP. There is a good reference site here, and the C++ FAQ is another good resource.
~AirlineTicket(); is the destructor for the class AirlineTicket
see this link for further reference
The destructor is called when you delete the object of that class, to free any memory allocated or resources being used by the object.
~ introduces a destructor. It's used because (a) it was available, ad (b) ~ is one (of several) mathematical notation for "not".
This indicates destructor of class.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr380.htm