Exception Handling Code Please explain it - c++

Please see the following code and its output - please explain me the code
void abc(int);
class A
{
public:
A()
{
cout<<"Constructor Called";
}
~A()
{
cout<<"Destructor called";
}
};
int main()
{
try
{
abc(-1);
}
catch(int p)
{
cout<<p<<endl;
}
return 0;
}
void abc(int p)
{
A * Aptr = new A[2];
if(p<0)
throw p;
}
Output:
Constructor Called
Constructor Called
-1
can anyone explain why is the destructor not being called as in the case of normal stack unwinding

This pointer:
A * Aptr = new A[2];
is a raw pointer. When it goes out of scope only the pointer itself is destroyed - nothing is done to the array it points to. So the array is not delete[]'ed and the destructors are not called. It's a typical example of a memory leak.
There're three typical solutions to the problem:
allocate the array itself on stack
use std::vector
use a smart pointer (not std::auto_ptr - it is not suitable for using with arrays.

The destructor is not called because the objects you allocate are never deleted. You would get the same output if you removed the throw.
If, on the other hand, you changed your function into this:
void abc(int p)
{
A A_array[2];
if (p<0)
throw p;
}
You would see that the destructor was called.

As mentioned elsewhere, C++ pointers do NOT delete the memory they point to when going out of scope. You have a few options:
The hard way - try and do the memory management yourself. This way lies memory leaks and buffer overflows. Try not to do this.
void abc(int p)
{
A * Aptr = new A[2];
if(p<0)
{
delete [] Aptr;
throw p;
}
delete [] Aptr;
}
Put the array on the stack and let the normal stack unwinding handle it:
void abc(int p)
{
A Aptr[2];
if (p<0)
throw p;
}
Instead of using a raw pointer to point to the newly allocated array, hold onto it using a smart pointer class like scoped_array or shared_array, or some other RAII class:
void abc(int p)
{
boost::scoped_array<A> Aptr (new A[2]);
if(p<0)
throw p;
}
}
2 and 3 are really the only safe options in C++ code that uses exceptions - if you use raw pointers and manual memory management, you WILL end up with memory leaks sooner or later. No matter how careful you are, exception safe code pretty much requires RAII.

In addition to the suggestions concerning boost::shared_array and boost::scoped_array you could also just use std::vector:
std::vector<A> array( 2 );
if( p < 0 )
throw p;
Note that your types should be copyable if you go this route, however, as std::vector will copy them around during insert or when internally resizing, et cetera.

Could it be because you are not calling delete on your A class? If you don't delete a dynamically allocated class the desnstructor is not called.

because you allocated on the heap. What gets freed are the variables holding the pointer to the array of objects. Not the objects themselves.

Aptr is a heap-allocated variable, not a stack variable. You need to explicitly delete it for the destructor to be called (and to free the memory).

If you would instead do this:
A a[2];
and not
A *Aptr = new A[2];
you'd get the destructor called.
Anything you allocate dynamically you will have to deallocate yourself.

You created the object on the heap. The destructor will be callen when you delete the object.
If you don't create the object on the heap, the destructor will be called as you expected.

Related

C++ Deleting a pointer to a object that contains another pointer

Let's say
class A {
A* array;
public:
A (){
array= new A [4];
}
~A (){
delete array;
}
}
How do we free an object if we create such an object on heap like
A* object_ptr =new A();
I'm a bit confused about freeing a pointer that points to an object containing another pointer.....
Calling
delete object_ptr;
after
A* object_ptr =new A();
will invoke the destructor of the A pointed to by object_ptr. That means, if you fix your wrong
~A (){
delete array;
}
to
~A (){
delete[] array;
}
your code will be fine and the internal pointer is freed correctly.
However, you really should use std::vector instead of new[]. It will make your life a whole lot easier. If you insist on new[], read about The Rule of Three.
Two things to note.
When deleting arrays you should use []. For example: delete [] array;
When deleting pointers the destructor of the allocated object will get called. You would call from your code: delete object_ptr; to delete your pointer.
Another important point to be aware of is what happens when you copy your object. If your object ever gets copies you will have problems where one destructor deletes the pointers out from under another object. This is why shared_ptr is a good alternative to raw pointers (see this question on how to use shared_ptr).

Managing destructors with pre-allocated memory and arrays

Hello So I'm experimenting with creating objects and arrays with preallocated memory. For instance I have this following code:
int * prealloc = (int*)malloc(sizeof(Test));
Test *arr = new(prealloc) Test();
Where test is defined as follows:
class Test {
public:
Test() {
printf("In Constructor\n");
}
~Test() {
printf("In Destructor\n");
}
int val;
};
In this scenario if I call delete it will actually release the memory which is bad, b/c maybe I'm using some type of memory manager so this will sure cause some problems. I searched in the internet and the only solution that I found was to call the destructor explicitly and then call free:
arr->~Test();
free(arr);
Is there another way to do this? is there perhaps a way to call delete and tell it to just call the destructor and not to release the memory?
My second problem was when working with arrays, like the previous example you can pass to new the pre-allocated memory:
int * prealloc2 = (int*)malloc(sizeof(Test) * 10);
Test *arr2 = new(prealloc2) Test[10];
If I call delete[] it will not only call the destructor for each element in the array but it will also release the memory which is something I don't want. The only way I have found that it should be done is to go through the array and call the destructor explicitly, and then call free. Like with the regular none array operators is there a way to tell the operator to just call the destructors without releasing the memory?
One thing I did notice was that the new operator for an array will actually use the first 4 bytes to store the size of the array (I only tested this in visual studio with a 32 bit build) That would help me know how many elements the array has but there is still one problem. What if the array is a pointer array? for example:
Test **arr2 = new Test*[10];
Could someone help me out with these questions please.
It's normal and expected to directly invoke the destructor to destroy objects you've created with placement new. As far as any other way to do things, about the only obvious alternative is to use an Allocator object (which, at least 99% of the time, will just be a wrapper around placement new and directly invoking the destructor).
Generally speaking, you do not want to use new[] at all. You typically want to allocate your raw memory with operator new (or possibly ::operator new) and release it with the matching operator delete or ::operator delete.
You create objects in that memory with placement new and destroy them by directly invoking the destructor.
There is no other way to do it but to explicitly call the destructor as delete will also attempt to free the memory.
Using preallocated memory with placement new should be fairly rare in your code - a typical use case is when you're dealing with direct memory mapped hardware interfaces when you want/need to map an object on top of a fixed memory address - and is something I'd normally consider a code smell.
If you want to tweak the memory management for a specific class, you're much better off either using an STL container with a custom allocator or overload operators new and delete for that specific class.
Yes, this is the only way to do it. There is an asymmetry in being allowed to define new but not delete. [ Well, you can do the latter but it can only get called when new throws an exception (not handled properly below!)
You can use a templated destroy to achieve the same result:
class Test
{
public:
Test() {
printf("In Constructor\n");
}
~Test() {
printf("In Destructor\n");
}
int val;
};
class Allocator
{
public:
static void* allocate(size_t amount) { return std::malloc(amount);}
static void unallocate(void* mem) { std::free(mem);}
static Allocator allocator;
};
Allocator Allocator::allocator;
inline void* operator new(size_t size, const Allocator& allocator)
{
return allocator.allocate(size);
}
template<class T>
void destroy(const Allocator& allocator, T* object)
{
object->~T();
allocator.unallocate(object);
}
int main()
{
Test* t = new (Allocator::allocator) Test();
destroy(Allocator::allocator, t);
return 0;
}

dealing with C++/C structures memory freeing

Must I free structure memory after using it? I have sample code:
struct aa
{
int a;
char * b ;
aa()
{
a=0;
b= new char[255];
}
} ;
aa *ss = new aa[3];
void fill()
{
aa * ssss = new aa;
aa * sss = new aa;
sss->a=10;
ss[0] = *sss;
cout<<ss[0].a<<"\n";
ss[1] = *sss;
cout<<ss[1].a<<"\n";
cout<<ssss[1].a<<"\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
fill();
delete(ss);
}
Must I do delete(ssss) at the end of fill?
Must I delete ss array of structure at the end of main?
Must I create destruct or to structure ss that frees *b memory?
What about classes is it the same logic?
Must I do delete(ssss) at the end of fill?
Yes, you must delete anything created with new. However, there's no need to use new here, just make it automatic:
void fill() {
aa ssss; // automatically destroyed on exit from the function
}
Must I delete ss array of structure at the end of main?
Yes, but it is an array, so must be deleted as an array:
delete [] ss;
^^
But again, there's no reason for this to be dynamically allocated:
aa ss[3]; // automatically destroyed on exit from the program
Must I create destruct or to structure ss that frees *b memory?
If you really want to use a raw pointer to manage the dynamic array, then yes. You will also need to think about a copy constructor and copy-assignment operator (per the Rule of Three) to make the class safe to use. Alternatively, use a smart pointer or container to manage the memory for you:
struct aa
{
int a;
std::vector<char> b ;
aa() : a(0), b(255) {}
} ;
What about classes is it the same logic?
Yes, the rule is always the same: anything created with new must be destroyed with delete. Managing objects is much easier if you avoid dynamic allocation where possible, and use smart pointers, containers and other RAII classes when you really do need it.
If you use new, you must use delete to avoid a memory leak. If you declare a variable on stack, it will be freed automatically when you exit the scope.
void something();
{
aa b = new aa();
// Do something
delete b; // You must use delete
}
void something();
{
aa b();
// Do something
// You don't have to use delete
}
In your specific case, it is not strictly necessary to use delete, because the program is going to terminate anyway and all the assigned memory will be freed by the OS.
It is still a good practice to do so, so as to be consistent (though there are some specific cases where you DON'T want to do this because freeing a lot of complex objects can take some time thus slowing down the program termination).
Anyhow, using naked pointers is not such a good idea in C++ since there are many so-called smart pointers (such as shared_ptr and unique_ptr) that take care of calling the destructor and freeing the memory after they run out of scope.
PS: In your code, you will have a memory leak, because the aa structure uses new inside the constructor and does not call delete in destructor.
YES
Please, please, please free your memory. I won't go into detail here, but take a look at this answer:
Can a memory block allocated by using operator new/malloc persist beyond end of program execution?
Rule of thumb in C/C++:
Allocated with new? free the memory with delete
Allocated with malloc, calloc, realloc? free the memory with free(void*)

How do I delete memory after manually invoking destructor?

I was reading this question Does calling a destructor explicitly destroy an object completely? where this situation comes up in code.
Object* aWidget = new Widget(); //allocate and construct
aWidget->~Object(); //destroy and DON'T deallocate
From the answers, I undrestand that the memory region is in fact not deallocated in this situation. My question is (more out of curiosity than anything):
How can I delete the memory pointed to by aWidget after the two lines of code above have executed? I would assume calling delete aWidget; would fail because it would try to run the destructor on an already-destructed object. Could you call free(aWidget) or something like that instead to just target the memory?
free would, factually speaking, be my best guess. However I don't think you can do anything without invoking UB. How did you arrive at a requirement to invoke the destructor like that?
Calling free on an object allocated with new is undefined behavior.
I suggest you keep it simple, and call delete.
However, if you want to do this, you can, in some cases, call delete even if you previously called the destructor explicitly. If you call it explicitly, you can view it as a function. The memory isn't freed, so I'm guessing setting member pointers to NULL after you destroy them would be enough to prevent you from running into any trouble. (because calling delete on a NULL pointer is a no-op).
For example, the following should be ok:
class A
{
public:
int * x;
A()
{
x = new int[10];
}
~A()
{
delete[] x;
x = NULL;
}
};
int main()
{
A* a = new A;
a->~A();
delete a;
return 0;
}

C++, will this cause memory leak?

I know that I can't get a reference of a local var. such as:
int& func1()
{
int i;
i = 1;
return i;
}
And I know that this is correct, but I have to delete it after calling func2()
int* func2()
{
int* p;
p = new int;
*p = 1;
return p;
}
int main()
{
int *p = func2();
cout << *p << endl;
delete p;
return 0;
}
If the function is like this:
MyClass MyFunction()
{
return new MyClass;
}
MyClass's whole definition is:
class MyClass
{
public:
MyClass() : num(1){}
MyClass(MyClass*) : num(10){}
int num;
};
Will this cause memory leak?
How should I avoid it?
the function returns an object not a pointer, so how can I delete it?
PS: the code comes from the book "Ruminations on C++" Chapter 10.
the original code is:
Picture frame(const Pictrue& pic)
{
// Picture has a constructor Picture(*P_Node)
// Frame_Pic derives from P_Node
// So the constructor Picture(*P_Node) will implicitly convert Frame_Pic to Picture.
return new Frame_Pic(pic);
}
MyClass MyFunction()
{
return new MyClass;
}
This is actually wrong.you are returning a pointer .
so it should be
MyClass* MyFunction()
if your function is as i mentioned above and if you are not deleting it after using it.it will leak memory.
How should I avoid it? the function returns an object not a pointer, so how can I delete it?
that is a compilation error.so the point of deleting it will not rise
If you delete the pointer returned from the funciton there is no memory leak. However this is error prone since it means that every client of the function must know that it should delete the return value. It's much better style to use a smart pointer (either shared_ptr or unique_ptr according to semantics).
The same goes to the Picture example. If this object correctly manages its resources (i.e. deletes in the destructor and has a good copy constructor and operator= (in accordance with the Rule of Three), then there is no memory leak.
With your updated MyClass that has the pointer constructor, I suppose you should write:
MyClass MyFunction() {
MyClass *ptr = new MyClass;
MyClass retval(ptr);
delete ptr; // the dynamically-allocated object isn't needed any more
return retval;
}
That happens to be exception-safe, since the constructor of MyClass can't throw, but as a general rule you really shouldn't ever call new without putting the result straight into a smart pointer:
MyClass MyFunction() {
std::unique_ptr<MyClass>(new MyClass);
return MyClass(ptr);
}
It's a fairly absurd situation anyway - if you're going to return by value, there's no reason to call new at all:
MyClass MyFunction() {
MyClass tmpvalue;
return &tmpvalue; // doesn't actually return the pointer, just an object
// constructed from it
}
And since the value of the pointer isn't even used by the pointer constructor, you could just as well write:
MyClass MyFunction() {
return 0; // returns an object constructed from a null pointer
}
In the original code your quote from the book, I guess that the class Picture has a data member of type P_Node*, in which it stores the pointer value, and calls delete on that pointer in its destructor. Hopefully the author also does something about the copy constructor and copy assignment operator of Picture, to prevent a double-free after the copy. I don't have the book, so I can't check my guess, but the code for Picture should show how it's done.
[Edit: oh, that's one of the books by Koenig and Moo. They are (more than) competent, so pretty certainly their Picture class handles the resource correctly. If it doesn't, it's because it's a deliberate example of Doing It Wrong.]
It's the same as your "func2" example. who ever call "frame" need to free the returning Picture in the end.
MyClass MyFunction()
{
return new MyClass;
}
is incorrect, because operator new returns a pointer to MyClass, but your function returns MyClass, not MyClass*
A simple check would be this:
If you're using N number of new in your program, then you've to use N number of compatible1 delete in your program to avoid memory leak2.
So are you doing that? Yes, in the first case (in which you're doing new int) you're doint that. There is no memory leak.
And rest of the post isn't clear enough to me!
1. By compatible delete, I mean if you're using new in the form of ptr = new T[M], then the compatible delete should be of the form of delete []ptr. Similarly, delete ptr is compatible with ptr = new T.
2. Of course, if you're using some smart pointers, then you don't have to use delete explictly.