Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc within constructor safe?

Tags:

c++

If I allocate memory with malloc (or new/new[]) within a class constructor, is that bit of memory safe from being overwritten?

class stack {
  private:
    int * stackPointer;
  public:
    stack (int size) {
      stackPointer = (int *) malloc (sizeof(int) * stackSize);
    }
    int peek (int pos) {
      return *(stackPointer + pos); //pos < size
    }
}
like image 409
texasflood Avatar asked May 13 '26 17:05

texasflood


1 Answers

malloc/new within a constructor is safe, provided you follow the rule of three. With malloc/new you now have a resource that you have to explicitly take care to release at the right times.

Therefore: you must define a copy constructor, an assignment operator, and a destructor that will free the memory. If you don't, the class can be misused and cause you a lot of problems.

If you want to avoid having to define these extra functions, use std::vector instead, which handles them for you.

like image 105
nneonneo Avatar answered May 15 '26 07:05

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!