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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With