简体   繁体   中英

C++ dynamic memory allocation of struct inside class via pointers is assigned nullptr “sometimes”

I have a simple example. I have a class, inside of it I have a struct that includes a pointer of type double. Inside that class, using a function therein, I intend to allocate dynamic memory using pointers. Out of curiosity, why does when I compile sometimes (50% of the time I compile) these pointers are initialized to be null and sometimes not?

A minimally-working example starting with the header file could be:

class house{

    struct room{
        double *roomPtr;
    } roomObj;

    room *myRoom = &roomObj;

public:
    void startPainting();

private:
    void paintRoom();
};

As for my cpp file, then it may be summarized (via a minimal example, as above) as:

void house::paintRoom(){
    if (myRoom->roomPtr != nullptr){
        myRoom->roomPtr = new double[someNbr];
    }
    else{
        cout << "Allocation failed !" << endl;
    }
}

For convenience sake, consider that in this class the public function's job is to simply allocate the memory (never mind freeing for now) -- ie

void house::startPainting(){
    paintRoom();
}

Anyway, when compiling the main (by simply creating an object of the class and running the public function...), sometimes (almost every other time) I get "Allocation failed!" -- ie the pointer was null. Is this typical, or am I doing something wrong?

Also, I understand that I may instead of using the above approach to allocate memory, I can per se do the following without the additional pointer(s):

roomObj.roomPtr = new double[someNbr]; 

This always works, but then again I am just curious why the above doesn't always work. May you please shed some insight on my shortcoming(s) ?

Thanks !

You need to assign the pointer roomPtr to a default value, such as in class' constructor. The memory in these objects are initialized in an implementation-defined way, so you may randomly get it assigned to a null value but it is not guaranteed.

For example, this modification would be better and provide consistent behavior:

house::house() : roomObj(), myRoom(&roomObj) {
   myRoom->roomPtr = nullptr;
}

As a side note, it doesn't fully make sense to me why you have a second member variable that is just pointing to some memory within the same class when you have a separate member variable describing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM