Access Violation

I just completed a project and I thought that I was done and now I am getting an exception thrown that says:

Exception thrown at 0x7793D9CB (ucrtbased.dll) in Project18.exe: 0xC0000005: Access violation reading location 0xCCCCCCBC.

This gets thrown in my destructor and now I have a green squiggly line from visual studio and when I put the cursor over it, it says that ptr (pointer used as a c-string) is uninitialized. I set up my pointer exactly how my instructor did in his example so I cannot make sense of what this all means and how to fix it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

namespace cs_mystring
{
	class MyString
	{
	public:
		MyString();
		MyString(const char* inString);
		MyString(const MyString& right);
		~MyString();
		friend std::ostream& operator << (std::ostream& out, const MyString& right);
		char& operator [] (int index);
		char operator [] (int index) const;
		friend bool operator < (const MyString& left, const MyString& right);
		friend bool operator <= (const MyString& left, const MyString& right);
		friend bool operator > (const MyString& left, const MyString& right);
		friend bool operator >= (const MyString& left, const MyString& right);
		friend bool operator == (const MyString& left, const MyString& right);
		friend bool operator != (const MyString& left, const MyString& right);
		MyString operator = (const MyString& right);
		size_t length()const;
		
	private:
		char *ptr;
	};
}





  MyString::MyString(const MyString& right) // Green squiggly line here
	{
		if (this != &right) {
			ptr = new char[strlen(right.ptr) + 1];
			strcpy(ptr, right.ptr);
		}
	}




MyString::~MyString()
	{
		delete[] ptr; // exception thrown here
	}
Last edited on
I figured it out. Got rid of the if statement above and noticed that my return statement in my = function was in the wrong place. Seems to be working good now.
But did you allow for self assignment? An else statement associated with that if would do that.
The copy constructor is how my instructor set his up in his example. I accidentally put that if statement.
Topic archived. No new replies allowed.