Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ int* wrapper yields large number rather than the int assigned

I’m trying to create a wrapper for int* in C++. Currently, it’s not going very well.

For the sake of testing, I’ve included 2 very taboo lines at the start, please ignore them.

#include <bits/stdc++.h>
using namespace std;

class Number {
    public:
    int32_t* value_32;
    Number(int32_t value) {
        value_32 = &value;
    }
};

int main() {
    int32_t v = 13;
    Number* n = new Number(v);
    cout << *(n->value_32) << "\n";
}

I would expect this code yields an output of 13, but it gives a random large number, ex: 1833022464. Why is this the case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: changing int32_t to int yields the same problem

>Solution :

You’re taking the address of a temporary. The lifetime of value ends, and value_32 is left pointing to invalid memory. Dereferencing it invokes undefined behavior. Seeing a different number than you expect is one outcome. The number you expected is another valid outcome. Or your program crashing.

Now, you could pass a reference to an int, but even there you have to worry about lifetime issues.

class Number {
public:
    int32_t* value_32;

    Number(int32_t &value) : value_32(&value) { }
};

Raw pointers in modern C++ are rarely necessary, so you’d really want to ask yourself why you’re writing code like this, and whether there’s a better way to accomplish your goal.

I would also suggest you read:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading