Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get "0xC0000005: Access violation reading location 0x0000000000000000"

So in one getter method I’m simply trying to get the length of a c-style string (c-style strings give me headaches) and it works everywhere else in the code except on 1 line stated below the code

#include <iostream>
#include <cstring>
#pragma warning(disable : 4996)

using namespace std;

class MyString
{
private:
    char *str;
public:
    int get_length() const { return strlen(str); }
    char get_string() const { return *str; }
    void display_obj() const
    {
        cout << str << " : " << get_length() << endl;
    }
    MyString()
        :str{nullptr}
    {
        str = new char[1];
        str = '\0';
    }
    MyString(const char *s)
        :str{nullptr}
    {
        str = new char[strlen(s) + 1];
        strcpy(str, s);
    }
    MyString(const MyString &source)
        :str{ nullptr }
    {
        str = new char[strlen(source.str) + 1];
        strcpy(str, source.str);
    }
    MyString(MyString &&source)
        :str{ source.str }
    {
        source.str = nullptr;
    }
    MyString &MyString::operator=(const MyString &source)
    {
        if (this == &source)
            return *this;
        delete[] str;
        str = new char[strlen(source.str) + 1];
        strcpy(str, source.str);
        return *this;
    }
    MyString &MyString::operator=(MyString &&source)
    {
        if (this == &source)
            return *this;
        delete[] str;
        str = source.str;
        source.str = nullptr;
        return *this;
    }
    ~MyString() { delete str; }
};

int main()
{
    MyString a{ "hello" };
    MyString b;
    b.display_obj();
    b = a;
    b.display_obj();
    b = "Tatarusanu";
    b.display_obj();
    system("pause");
    return 0;
}

and here

int get_length() const { return strlen(str); }

I get thrown the exception "Exception thrown at 0x00007FF98602F621 (ucrtbased.dll) in Project1.exe: 0xC0000005: Access violation reading location 0x0000000000000000" and I have no idea why. Any suggestions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

MyString()
    :str{nullptr}
{
    str = new char[1];
    //str = '\0'; // <-- here is your mistake
    str[0] = '\0'; // do this instead
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading