0

It seems this problem is the so-called dangling pointer problem. Basically I'm trying to parse a pointer into a function (that stores the pointer as a global variable) inside a class, and I want the pointer to be stored in that class and can be used now and then. So from inside the class, I can manipulate this pointer and its value which is outside of the class.

I simplified the code and re-created the situation as the following:

main.cpp

#include <iostream>
#include "class.h"

using namespace std;

void main() {
    dp dp1;
    int input = 3;
    int *pointer = &input;
    dp1.store(pointer);
    dp1.multiply();
}

class.h

#pragma once

#include <iostream>

using namespace std;

class dp {

public:
    void store(int *num); // It stores the incoming pointer.
    void multiply(); // It multiplies whatever is contained at the address pointed by the incoming pointer.
    void print();


private:
    int *stored_input; // I want to store the incoming pointer so it can be used in the class now and then.

};

class.cpp

#include <iostream>
#include "class.h"

using namespace std;

void dp::store(int *num) {
    *stored_input = *num;
}

void dp::multiply() {
    *stored_input *= 10;
    print();
}

void dp::print() {
    cout << *stored_input << "\n";
}

There is no compile error but after running it, it crashes.

It says:

Unhandled exception thrown: write access violation.

this->stored_input was 0xCCCCCCCC.

If there is a handler for this exception, the program may be safely continued.

I pressed "break" and it breaks at the 7th line of class.cpp:

*stored_input = *num;
Community
  • 1
  • 1
Freeman
  • 5
  • 3
  • ***this->stored_input was 0xCCCCCCCC.*** You did not initialize stored_input. http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations – drescherjm Dec 24 '16 at 15:36
  • Remember stored_input is a pointer. – drescherjm Dec 24 '16 at 15:38
  • Just a suggestion here, but consider taking in a [`unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) this will let your class control the pointer rather than your class depending upon a variable it doesn't own. Consider for example: `void bad(dp& param) { int input = 3; dp.store(&input); }` Now the passed `dp` contains an invalid value :( – Jonathan Mee Dec 24 '16 at 15:44

1 Answers1

3

It is not a dangling pointer, but a not initialized, you probably want:

void dp::store(int *num) {
    stored_input = num;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302