Question

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.

Was it helpful?

Solution

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..

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top