c++ - 类(class)访问违规阅读位置

标签 c++ memory runtime-error

我对 C++ 很陌生,我一直在玩弄 指针和类有点。到目前为止我遇到了一个问题 我一直无法找到解决方案:

Unhandled exception at 0x77F87508 (msvcr110d.dll) in RAII.exe: 0xC0000005: Access violation reading location 0xCCCCCCC0.

好像跟我访问指针有关系 我无权访问。

主要.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;
}

例子.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;
}

例子.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_

所以,我基本上做的是在 构造函数并在析构函数中释放它。

欢迎任何帮助!提前致谢:D

最佳答案

你的代码有错误:

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
}

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

关于c++ - 类(class)访问违规阅读位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991687/

相关文章:

c++ - 更改 CMFCListCtrl 的默认排序箭头

c++ - 如何将boost udp套接字绑定(bind)到特定接口(interface)

c# - 如何在 Linux 中确定 Mono/C# 中的空闲内存(没有外部 DLL)

android.util.AndroidRuntimeException : You cannot combine swipe dismissal and the action bar

c++ - 尝试让 while 循环工作,当输入符号而不是字符时,该循环会中断

c++ - Bad_alloc 问题

python - 获取用户内存消耗的脚本或命令

C++ 错误 : terminate called after throwing an instance of 'std::bad_alloc'

compilation - 错误:找不到或加载主类Hello.class

c++ - OpenMP omp_get_num_threads()V.S. omp_get_max_threads()