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

returning the value of private dynamic int results in seg fault

I’m doing a quick test to see how to get the value of a dynamically allocated private data member to another dynamically allocated variable outside of the class, but I’m having trouble returning their value. Whenever I try, I result in a segmentation fault at runtime. I’ve been slowly simplifying the code and even reduced to an int data type I can’t get it to work. Here’s the code:

#include <iostream>
class testing{
    public:
        testing();
        int getValue();
    private:
        int* asdf;
};
int main(){
    int* test = NULL;
    int test2, test3;
    testing test1;

    test2 = test1.getValue();
    test  = new int(test2);
    test3 = *test;

    std::cout << test3 << std::endl;

    return 0;
}
testing::testing(){
    int* asdf = new int(3);
}
int testing::getValue(){
    return *asdf;
}

I expect the code to print out just 3, but it doesn’t. What am I messing up?

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

>Solution :

There is null pointer referencing problem in here. Allocate some memory and initialize the test or make test point some other int.

EDIT : As @songyuanyao pointed out, the constructor did not initialized original testing::asdf, but new local variable asdf. You also should remove int* specifier to avoid that problem.

int main(){
    int* test = NULL;    //null pointer. You did not give any valid address.
    int test2, test3;
    testing test1;

    test2 = test1.getValue();
    test  = new int(test2);
    test3 = *test;       //ERROR! Trying to dereference the null pointer

    std::cout << test3 << std::endl;

    return 0;
}
testing::testing(){
    asdf = new int(3);  // removed int*, as original expression does hide your member variable.
}

Additionally, naked new expression easily produces memory leak problem. I recommend you to be familiar to the smart pointers in C++.

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