0
看来这个问题是所谓的悬挂指针问题。基本上我试图解析一个指针到一个函数中(将指针存储为一个全局变量),并且我希望指针被存储在该类中,并且可以立即使用。所以从课内,我可以操作这个指针和它在课堂外的值。C++指针崩溃(未初始化)
我简化的代码并重新创建的情况如下所示:
的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";
}
有没有compi le错误,但运行后,它崩溃。
它说:
未处理的异常抛出:写访问冲突。
this-> stored_input是0xCCCCCCCC。
如果有这种异常的处理程序,程序可能会安全地继续。
我按下“破”,它打破了在class.cpp的七号线:
*stored_input = *num;
*** this-> stored_input was 0xCCCCCCCC。***您没有初始化stored_input。 http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations – drescherjm
记住stored_input是一个指针。 – drescherjm
这里只是一个建议,但考虑在['unique_ptr'](http://en.cppreference.com/w/cpp/memory/unique_ptr)这将让你的类控制指针,而不是你的类取决于变量它不拥有。考虑例如:'void bad(dp&param){int input = 3; dp.store(输入); }'现在传递的'dp'包含一个无效值:( –