简体   繁体   中英

Access violation reading location in class

I am quite new to C++ and I have been playing around with pointers and classes a bit. I have run into a problem that so far I haven't been able to find a solution to:

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

It seems to have something to do with me accessing a pointer that I don't have access to.

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

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

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_

So, what I basically do is allocate memory in the constructor and deallocate it in the destructor.

Any help is welcome! Thanks in advance :D

You have a mistake in your code:

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
}

For that reason when you call delete m_c; in destructor you end up freeing the memory which does not belong to your application, hence experience the crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM