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

smootherstep
  • 157
  • 3
  • 10
  • `_EXAMPLE_HPP_` is a [bad choice of identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Apr 13 '13 at 19:02
  • What would a good choice be for an identifier? – smootherstep Apr 13 '13 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 '13 at 19:07
  • Some editors also have tools for adding the the definition from the guid of the file. –  Apr 13 '13 at 19:11

1 Answers1

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.

Alexander Shukaev
  • 16,674
  • 8
  • 70
  • 85