Dynamically allocating new object in constructor - c++

So given this simple scenario:
class A{
public:
A(){
n = new int(10);
}
~A(){
delete n;
}
int* n;
};
int main(){
A* a = new A();
}
Can this cause heap corruption (problems in general), since a-pointer hasn't finished allocating, while I'm making a new allocation?
If so, using std::vector inside heap constructors in also prohibited, right?
Thank you.

Your a pointer has finished allocating.
New works as follows (oversimplified)
Allocate
Construct
So in your case
Allocate A
Construct A
Allocate int
Construct int - initialize
Finish Construct A
This ignores cases involving exceptions..

There is no such thing as a "heap constructor", and no, you cannot corrupt the heap by newing memory inside a constructor of an object on the heap. The memory for the new A is fully allocated at the time A::A() is invoked. What you're doing is both correct and extremely common. Your constructor need never be concerned with whether the object being constructed is allocated on the stack or heap. Otherwise, pointers and classes would be pretty useless.

if "new" throw an exception then the object is not allocated (beware any allocation made BEFORE "new" need to be deallocated else you'll have a memory leach)..
Exceptions are thinked to be used as error system since constructor can't return a error code.
myclass::myclass()
{
param1 = new type1(); //successfull
try
{
param2= new type2(); //may fail
}
(...)
{
delete param1; //need to deallocate
}
}
That's a bit overkill, I prefer to have no exceptions in constructors at all, some people make entire frameorks with constructors than can throw exceptions..
anyway any other bug in the allocator can cause:
segmentation fault (access out-of-range value)
heap corruption (overwrite data that is in memory range but that is not tecnically owned bythe object)
infinite loop (you need to abort the program externally or it will never exit the allocator).
Those are the mains problem that you can also have with normal code of course. The default allocator however will not give any problem, at least can throw a "out of memory" exception. if you not have enough ram.

Related

How to deal with Exceptions in C++ programming when there are a lot of memory allocation

I am a novice in the field of C++ program and I read the book More Effective C++. There is one specific section about how to deal with C++ exceptions. In terms of the item 10, the author claims that we should avoid the memory leak in the constructors as the following example.
BookEntry::BookEntry(const string& name, const string& address,
const string& imageFileName,
const string& audioClipFileNmae):theName(name), theAddress(address),
theImage(0), theAudioClip(0) {
try {
if (imageFileName != "") {
theImage = new Image(imageFileName);
}
if (audioClipFileName != "") {
theAudioClip = new AudioClip(audioClipFileName);
}
}
catch (...) {
delete theImage;
delete theAudioClip;
}
In this way, we can avoid the source leak when there is an error of creating theImage or theAudioClip. My question is that if there is a lot of functions which contains memory allocation as the following.
void BookEntry::test1() {
float *A = new float[1000];
float *B = new float[1000];
....
delete [] A;
delete [] B;
}
Do I have to use the try catch structure to deal with the danger of memory leak? Usually, I prefer to just testing whether the pointer A and pointer B are null pointer or not and if the allocation fail, I will abort the program immediately.
You are probably misunderstanding what the book meant by "memory leak". A failure to allocate may be the eventual result of a memory leak, but the two things are not the same.
What the book is talking about is what happens if AudioClips constructor fails. Not the memory allocation of AudioClip, but AudioClip's constructor. Because remember, constructors only have one way to signal failure: throwing an exception.
If it throws, and someone in the call stack of your BookEntry constructor invocation catches that exception, then the previously allocated theImage will never be cleaned up. BookEntry's constructor never successfully completed, so its destructor will never be called (since the object never existed, you can't delete it).
This is why nowadays (aka: post-C++11), we would store those allocated members in smart pointers. While BookEntry's destructor will never be called, the destructors for any of its successfully constructed subobjects will be called. So if theImage is a unique_ptr<Image>, its destructor will be called, which will delete the Image it holds.
Usually, I prefer to just testing whether the pointer A and pointer B are null pointer or not and if the allocation fail, I will abort the program immediately.
Then exceptions for memory allocation failure are even better for you, since you don't have to test for anything. You just let the allocation failure exception reach main, and your program will terminate.
However, the above issue is not about allocation failure exceptions.

Why not call Destructor in C++?

I studding C++ concept. I'm confused in constructor and Destractor concept. Destructor will be invoked implicitly by the compiler upon exit from the program. But in my program, only constructor called.
#include <iostream>
using namespace std;
class A
{
int i;
public:
A()
{
cout<<"Constructor call"<<endl;
}
~A()
{
cout<<"Destructtor call"<<endl;
}
};
int main()
{
A *a = new A();
}
Output:
Constructor call
So, I have question : Why destructor not call implicit by the compiler upon exit program?
Why destructor not call implicit by the compiler upon exit program?
Because dynamically allocated objects are not destroyed automatically. That is how the language has been specified. Tracking the destruction of dynamic objects would require runtime / memory overhead.
Solution: Do not leak dynamically allocated objects.
There are 2 "types" of variable lifetime in C++. Dynamic and automatic.
Automatic is something like :
void foo()
{
int i; // automatic storage
} // destroys i
Here, i will be destructed the moment it leaves scope (after foo returns). You can check this for yourself by making your object have an automatic lifetime:
int main()
{
A a; // calls A's constructor and allocates memory.
} //calls A's destructor and frees the memory used.
You'll see that both the constructor and the destructor will get called.
The second form is dynamically allocated memory. You can dynamically allocate memory by using new (like you did) and free that memory by using delete. The compiler won't do this for you.
This means that, to destruct your object you have to call delete explicitly yourself:
int main()
{
A* a = new A();
delete a; // calls A's destructor and frees the memory used.
}
If you do not call delete (like your code) then the moment the program leaves main the pointer a is destroyed and now we have a piece of memory that nothing can reach and thus nobody can clean up (with delete) which means you're leaking memory.
However, modern operating systems reclaim all memory used by the program automatically the moment the program ends so at this point it won't matter too much. This does mean your destructor won't be called as you've just witnessed.
Dynamically allocated memory allows you to do some nifty tricks like controlling the lifetime of your objects to the point where you want to destroy them explicitly yourself with delete. The problem with using new and delete is that it's so easy to forget a single delete and your program will already leak memory, which is why it's advised to stay away from this way of allocation.
If for some reason you absolutely need dynamic lifetime then use a smart pointer like std::unique_ptr that will call new and delete for you the moment it goes out of scope.
You create the object dynamically with new. The destructor will only be called when the objected is deleted with delete.
To prevent memory leaks, you could/should use smart pointers like unique_ptr.
In any case, the memory itself will of course be released when the process ends.
The destructor is never called in your code because the object is never destroyed.
You dynamically allocate the A object and you never deallocate it. Add delete a; into main() and you'll see the destructor in action:
int main()
{
A *a = new A();
delete a;
return 0;
}
In your main function, you create a pointer variable that you must delete it by delete a at end of main function.
Because you have a memory leak. You dynamically created an object with new, promising that you would manage the lifetime of the object and clean it up later with delete. Then you broke that promise.
If you create an object in the usual fashion:
A a;
then it will be destroyed automatically for you.

Leaking in constructor

Do I leak if I allocate memory with new in the constructor of an object and immediately after I throw an exception?
The object shouldn't be constructed at all and thus no destructor will be called, but what about that memory?
e.g.
MyObject() {
data = new char[200]; // Will this be leaked?
if(something_is_wrong)
throw exception();
}
It will leak. Once you have gotten a pointer from new it eventually needs to be deleted. The solution is to make data a smart pointer (or in this case, probably a std::string); while MyObject's destructor won't be called, data members' destructors are called.
Yes, it will be a leak unless data is kind of handle, smart pointer and not a raw pointer char* data. A safe variant of this is:
class MyObject {
std::vector<char> data; // or some handle/smart pointer (i.e. unique_ptr)
// it might be just std::string
public:
MyObject( int sz) : data( sz) {}
};
In this case the memory used is now managed by vector. You can of course do it by yourself what is actually done in vector already and is exception safe. This is you can use approach similar to std::uninitialized_fill.
Unless data is a smart pointer (or, more generally, any object that frees the memory passed to it when it destructs) you will leak memory.
The new will need to be balanced with a delete[] (note the []). It's important to note that, since a MyObject instance was not created, the destructor to MyObject will not be called so you cannot rely on any memory cleanup there.
Two alternatives.
free the memory before the throw statement.
Make data a smart pointer (if it isn't already).
2 is preferred - by exploiting RAII it makes code more stable.
The situation that you sketch,
MyObject() {
data = new char[200]; // Will this be leaked?
if(something_is_wrong)
throw exception();
}
will1 leak unless automatic garbage collection is used (and even so it may still leak).
This case is very easily dealt with by using an appropriate standard library container:
MyObject()
{
string data( 200, '\0' );
if(something_is_wrong)
throw exception();
}
And in general preferentially use standard library containers instead of all this new'ing, and if there isn't a suitable container, use smart pointers such as std::unique_ptr.
In short, there's not really a problem, not any more than a call to std::terminate is a problem (just remove the call, or don't do it in the first place).
However, if you define a custom allocation function for the class, and forget to define a corresponding deallocation function, then throwing an exception from a constructor can leak memory.
As a learner simply don't define allocation functions.
As a professional remember to do it properly if at some time you should really need it.
1) Under the reasonable assumption that you're not using a smart pointer to guarantee cleanup and asking this question without mentioning the smart pointer.

Stack Overflow when deleting this Pointer

I have the following code and I get stack overflow error can anyone please explain me What's wrong here. from my understanding this pointer points to current object so why I cant delete it in a destructor;
class Object
{
private:
static int objCount;
public:
int getCount()
{
int i =10;
return i++;
}
Object()
{
cout<< "Obj Created = "<<++objCount<<endl;
cout <<endl<<this->getCount()<<endl;
}
~Object()
{
cout<<"Destructor Called\n"<<"Deleted Obj="<<objCount--<<endl;
delete this;
}
};
int Object::objCount = 0;
int _tmain(int argc, _TCHAR* argv[])
{
{
Object obj1;
}
{
Object *obj2 = new Object();
}
getchar();
return 0;
}
You're doing delete this; in your class's destructor.
Well, delete calls the class's destructor.
You're doing delete this; in your class's destructor.
...
<!<!<!Stack Overflow!>!>!>
(Sorry guys I feel obliged to include this... this might probably spoil it sorrrryyyy!
Moral of the boring story, don't do delete this; on your destructor (or don't do it at all!)
Do [1]
Object *obj = new Object();
delete obj;
or much better, just
Object obj;
[1]#kfsone's answer more accurately points out that the stack overflow was actually triggered by obj1's destructor.
'delete this' never makes sense. Either you're causing an infinite recursion, as here, or you're deleting an object while it is still in use by somebody else. Just remove it. The object is already being deleted: that's why you're in the destructor.
The crash you are having is because of the following statement:
{
Object obj1;
}
This allocates an instance of "Object" on the stack. The scope you created it in ends, so the object goes out of scope, so the destructor (Object::~Object) is invoked.
{
Object obj1;
// automatic
obj1.~Object();
}
This means that the next instruction the application will encounter is
delete this;
There are two problems right here:
delete calls the object's destructor, so your destructor indirectly calls your destructor which indirectly calls your destructor which ...
After the destructor call, delete attempts to return the object's memory to the place where new obtains it from.
By contrast
{
Object *obj2 = new Object();
}
This creates a stack variable, obj2 which is a pointer. It allocates memory on the heap to store an instance of Object, calls it's default constructor, and stores the address of the new instance in obj2.
Then obj2 goes out of scope and nothing happens. The Object is not released, nor is it's destructor called: C++ does not have automatic garbage collection and does not do anything special when a pointer goes out of scope - it certainly doesn't release the memory.
This is a memory leak.
Rule of thumb: delete calls should be matched with new calls, delete [] with new []. In particular, try to keep new and delete in matching zones of authority. The following is an example of mismatched ownership/authority/responsibility:
auto* x = xFactory();
delete x;
Likewise
auto* y = new Object;
y->makeItStop();
Instead you should prefer
// If you require a function call to allocate it, match a function to release it.
auto* x = xFactory();
xTerminate(x); // ok, I just chose the name for humor value, Dr Who fan.
// If you have to allocate it yourself, you should be responsible for releasing it.
auto* y = new Object;
delete y;
C++ has container classes that will manage object lifetime of pointers for you, see std::shared_ptr, std::unique_ptr.
There are two issues here:
You are using delete, which is generally a code smell
You are using delete this, which has several issues
Guideline: You should not use new and delete.
Rationale:
using delete explicitly instead of relying on smart pointers (and automatic cleanup in general) is brittle, not only is the ownership of a raw pointer unclear (are you sure you should be deleting it ?) but it is also unclear whether you actually call delete on every single codepath that needs it, especially in the presence of exceptions => do your sanity (and that of your fellows) a favor, don't use it.
using new is also error-prone. First of all, are you sure you need to allocate memory on the heap ? C++ allows to allocate on the stack and the C++ Standard Library has containers (vector, map, ...) so the actual instances where dynamic allocation is necessary are few and far between. Furthermore, as mentioned, if you ever reach for dynamic allocation you should be using smart pointers; in order to avoid subtle order of execution issues it is recommend you use factory functions: make_shared and make_unique (1) to build said smart pointers.
(1) make_unique is not available in C++11, only in C++14, it can trivially be implemented though (using new, of course :p)
Guideline: You shall not use delete this.
Rationale:
Using delete this means, quite literally, sawing off the branch you are sitting on.
The argument to delete should always be a dynamically allocated pointer; therefore should you inadvertently allocate an instance of the object on the stack you are most likely to crash the program.
The execution of the method continues past this statement, for example destructors of local objects will be executed. This is like walking on the ghost of the object, don't look down!
Should a method containing this statement throw an exception or report an error, it is difficult to appraise whether the object was successfully destroyed or not; and trying again is not an option.
I have seen several example of usage, but none that could not have used a traditional alternative instead.

double free without any dynamic memory allocation

In general, what could cause a double free in a program that is does not contain any dynamic memory allocation?
To be more precise, none of my code uses dynamic allocation. I'm using STL, but it's much more likely to be something I did wrong than for it to be a broken implmentation of G++/glibc/STL.
I've searched around trying to find an answer to this, but I wasn't able to find any example of this error being generated without any dynamic memory allocations.
I'd love to share the code that was generating this error, but I'm not permitted to release it and I don't know how to reduce the problem to something small enough to be given here. I'll do my best to describe the gist of what my code was doing.
The error was being thrown when leaving a function, and the stack trace showed that it was coming from the destructor of a std::vector<std::set<std::string>>. Some number of elements in the vector were being initialized by emplace_back(). In a last ditch attempt, I changed it to push_back({{}}) and the problem went away. The problem could also be avoided by setting the environment variable MALLOC_CHECK_=2. By my understanding, that environment variable should have caused glibc to abort with more information rather than cause the error to go away.
This question is only being asked to serve my curiosity, so I'll settle for a shot in the dark answer. The best I have been able to come up with is that it was a compiler bug, but it's always my fault.
In general, what could cause a double free in a program that is does not contain any dynamic memory allocation?
Normally when you make a copy of a type which dynamically allocates memory but doesn't follow rule of three
struct Type
{
Type() : ptr = new int(3) { }
~Type() { delete ptr; }
// no copy constructor is defined
// no copy assign operator is defined
private:
int * ptr;
};
void func()
{
{
std::vector<Type> objs;
Type t; // allocates ptr
objs.push_back(t); // make a copy of t, now t->ptr and objs[0]->ptr point to same memory location
// when this scope finishes, t will be destroyed, its destructor will be called and it will try to delete ptr;
// objs go out of scope, elements in objs will be destroyed, their destructors are called, and delete ptr; will be executed again. That's double free on same pointer.
}
}
I extracted a presentable example showcasing the fault I made that led to the "double free or corruption" runtime error. Note that the struct doesn't explicitly use any dynamic memory allocations, however internally std::vector does (as its content can grow to accommodate more items). Therefor, this issue was a bit hard to diagnose as it doesn't violate 'the rule of 3' principle.
#include <vector>
#include <string.h>
typedef struct message {
std::vector<int> options;
void push(int o) { this->options.push_back(o); }
} message;
int main( int argc, const char* argv[] )
{
message m;
m.push(1);
m.push(2);
message m_copy;
memcpy(&m_copy, &m, sizeof(m));
//m_copy = m; // This is the correct method for copying object instances, it calls the default assignment operator generated 'behind the scenes' by the compiler
}
When main() returns m_copy is destroyed, which calls the std::vector destructor. This tries to delete memory that was already freed when the m object was destroyed.
Ironically, I was actually using memcpy to try and achieve a 'deep copy'. This is where the fault lies in my case. My guess is that by using the assignment operator, all the members of message.options are actually copied to "newly allocated memory" whereas memcpy would only copy those members that were allocated at compile time (e.g. a uint32_t size member). See Will memcpy or memmove cause problems copying classes?. Obviously this also applies to structs with non-fundamental typed members (as is the case here).
Maybe you also copied a std::vector incorrectly and saw the same behavior, maybe you didn't. In the end, it was my entirely my fault :).