0

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

4
  • _EXAMPLE_HPP_ is a bad choice of identifier.
    – chris
    Apr 13, 2013 at 19:02
  • What would a good choice be for an identifier? Apr 13, 2013 at 19:06
  • 1
    I usually use PROJECTNAME_FILENAME_EXTENSION. With some variation of that, I see a trailing _ or _DEFINED pretty commonly as well.
    – chris
    Apr 13, 2013 at 19:07
  • Some editors also have tools for adding the the definition from the guid of the file.
    – user995502
    Apr 13, 2013 at 19:11

1 Answer 1

8

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.

2
  • I have no idea on how I missed this! Thanks a lot :D Apr 13, 2013 at 19:05
  • @0x499602D2, I was so focused on trying to find where it was being copied/moved, so as to be a Rule of N thing.
    – chris
    Apr 13, 2013 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.