Home > Blockchain >  returning the value of private dynamic int results in seg fault
returning the value of private dynamic int results in seg fault

Time:03-02

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?

CodePudding user response:

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 .

CodePudding user response:

You've got half of the solution in your getValue accessor function - try implementing a mutator function to modify asdf instead of calling new in testing's constructor.

  • Related