Is Malloc in the constructor safe?
If I allocate memory using malloc
(or new
/ new[]
) in the class constructor, is that bit of memory overwrite safe?
class stack {
private:
int * stackPointer;
public:
stack (int size) {
stackPointer = (int *) malloc (sizeof(int) * stackSize);
}
int peek (int pos) {
return *(stackPointer + pos); //pos < size
}
}
source to share
malloc
/ new
inside a constructor is safe if you follow the rule of three. With malloc
/ you new
now have a resource that you must explicitly free at the right time.
Hence: you must define a copy constructor, an assignment operator and a destructor that will be free
memory. If you don't, the class can be misused and cause a lot of problems.
If you want to avoid having to define these additional functions, instead use std::vector
one that handles them for you.
source to share
Protecting C ++ languages ββis just what the language protects.
If you do some fancy games with C pointers, you may end up finding and overwriting the allocated memory. He considered the exact opposite of best practice, but it can happen.
Thus, "protection" is very similar to "hiding". Malloc inside the constructor will return pointers that are "hidden" based on the exposure the surrounding class decides to allow, but they are not protected in the sense of "memory fencing" or other more costly operations that the operating system / hardware platform may have overlapping between programs.
As far as βsafeβ it is, I would not recommend this practice, mainly because there is a chance you will not exit the constructor. If you don't fire inside the constructor, trying to properly clean up any mallocks that might fire would be a very difficult task to verify that it works correctly. Use instead new
, and put your memory in an object, and that way, at least in the event of a crash, you only have one way to allocate memory.
Malloc with C ++ means you have two memory allocation technologies and two different ways to interact. These are the four scenarios you will run into, and the chances that you will never run into testing them are good enough.
source to share
Technically, it is safe from being overwritten by others as long as you don't pass the handle to that memory to the outside world in some way possible. This way you can localize manipulations with this memory only to class members.
However, you cannot be 100% sure about this, as another programmer may have written the program in a way that could damage your memory. For example, if you passed the associated index to arrays.
source to share