访问违规阅读课堂上的位置

Eri*_*son 0 c++ memory runtime-error

我是C++的新手,我一直在玩指针和类.我遇到了一个问题,到目前为止我还没有找到解决方案:

RAII.exe中0x77F87508(msvcr110d.dll)的未处理异常:0xC0000005:访问冲突读取位置0xCCCCCCC0.

它似乎与我访问一个我无法访问的指针有关.

Main.cpp的:

#include <memory>
#include <iostream>
#include "Example.hpp"

void example()
{
    Example e;
}

int main()
{
    example();
    std::cout << "Press any key to exit";
    std::cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Example.cpp:

#include "Example.hpp"

Example::Example()
{
    m_a = new int(1);
    m_b = new int(2);
    m_b = new int(3);
}

Example::~Example()
{
    delete m_a;
    delete m_b;
    delete m_c;
}
Run Code Online (Sandbox Code Playgroud)

Example.hpp:

#ifndef _EXAMPLE_HPP_
#define _EXAMPLE_HPP_

#include <memory>
#include <iostream>

class Example
{
private:
    int *m_a;
    int *m_b;
    int *m_c;
public:
    Example();
    ~Example();
};

#endif _EXAMPLE_HPP_
Run Code Online (Sandbox Code Playgroud)

所以,我基本上做的是在构造函数中分配内存并在析构函数中释放它.

欢迎任何帮助!提前致谢

Ale*_*aev 7

您的代码中有错误:

Example::Example()
{
    m_a = new int(1);
    m_b = new int(2);
    m_b = new int(3); // <--- you probably meant it to be m_c
}
Run Code Online (Sandbox Code Playgroud)

因此,当您delete m_c;在析构函数中调用时,最终会释放不属于您的应用程序的内存,因此会遇到崩溃.