Bobby
Bobby

Reputation: 17

Read Access Violation _First was nullPtr

I have a default constructor, copy constructor, destructor, assignment operator, length, and string functions. When I call the copy constructor and try to print the value of the new char*, I get a Read Access Violation _First was nullptr. The debugger shows iosfwd code and breaks at the error, but I have no clue what this means. Any help would be awesome. This is where the debugger shows the error.

  static size_t __CLRCALL_OR_CDECL length(const _Elem *_First)
        {   // find length of null-terminated string
        return (*_First == 0 ? 0 // <- this line
            : _CSTD strlen(_First));
        }

These are my functions (also not that we were not allowed to use STRCPY)

 MyString::MyString() { //default constructor
    string = new char[6];
    int i = 0;
    for (i; i < strlen(string); i++) {
        string[i] = NULL;
    }
    string[i] = '\0';
}

    MyString::MyString(const MyString &s) { //copy constructor
    char* string = new char[strlen(s.string) + 1];
    int i = 0;
    for (i; i < strlen(s.string); i++) {
        string[i] = s.string[i];
    }
    string[i] = '\0';
}

    MyString::~MyString() { //destructor
    delete[] string;
    string = NULL;
}

    MyString& MyString::operator=(const MyString& s) { //assignment operator
    char* temp = new char[strlen(s.string) + 1];
    int i = 0;
    for (i; i < strlen(s.string); i++) {
        temp[i] = s.string[i];
    }
    temp [i] = '\0';
    delete[] string;
    string = temp;
    return *this;
}

    size_t MyString::length() const { //length of string
    return strlen(string);
}

    char* MyString::cString() { //string
    return string; 
}

    int main(int argc, const char * argv[]){
    MyString s;
    std::cout << "Empty: '" << s.cString() << "'\n";
    s = "hello";
    std::cout << "After operator=: '" << s.cString() << "'\n";
    {
        MyString t(s);
        std::cout << "After copy: '" << t.cString() << "'\n";
        s = t;
    }
}

Upvotes: 1

Views: 3022

Answers (1)

The Dark
The Dark

Reputation: 8514

This line in your copy constructor

char* string = new char[strlen(s.string) + 1];

Creates a new local variable called string which means that your member variable called string is never assigned a value.

Remove the char *

Upvotes: 5

Related Questions