C ++指针崩溃(未初始化)

时间:2016-12-24 15:34:17

标签: c++ pointers parameters crash

看来这个问题就是所谓的悬空指针问题。基本上我试图将指针解析为一个函数(将指针存储为全局变量)在一个类中,我希望指针存储在该类中,并且可以偶尔使用。所以从类中,我可以操作这个指针及其在类之外的值。

我简化了代码并重新创建了以下情况:

的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";
}

没有编译错误,但在运行之后,它崩溃了。

它说:

  

抛出未处理的异常:写入访问冲突。

     

this-&gt; stored_input是0xCCCCCCCC。

     

如果存在此异常的处理程序,则可以安全地继续该程序。

我按下&#34;休息&#34;它在class.cpp的第7行打破了:

*stored_input = *num;

1 个答案:

答案 0 :(得分:3)

它不是一个悬空指针,而是一个未初始化的指针,你可能想要:

void dp::store(int *num) {
    stored_input = num;
}
相关问题