Don't Understand Why I am Getting Exception: Access violation reading location 0x00000000

1

I am working on a class that works with c-strings and I have created a member function that returns the length of the calling object (which is a c-string). When I run the code I get Exception thrown at 0x0F63F6E0 (ucrtbased.dll) in Project5.exe: 0xC0000005: Access violation reading location 0x00000000. I cannot figure out how to fix this. I am not quite sure how much code I need but hopefully the snippet below will suffice.

MyString::MyString(const char* aString) //memberString is a    c-string object
{
    memberString = new char[length() + 1];
    strcpy(memberString, aString);
}

int MyString::length() //Exception gets raised here
{
    return strlen(memberString); //Exception gets raised here
}
c++
class
c-strings
strlen
asked on Stack Overflow Apr 19, 2019 by ashton

1 Answer

2

Your problem is that

  • length() need memberString to return size of stored data,
  • memberString need length() to be created.

I think that your constructor should not rely on other member function.

What about:

MyString::MyString(const char* aString) //memberString is a    c-string object
{
    memberString = new char[strlen(aString) + 1];
    strcpy(memberString, aString);
}
answered on Stack Overflow Apr 19, 2019 by Mathieu

User contributions licensed under CC BY-SA 3.0