Reputation: 3079
From reading other stackoverflow questions I am aware that this error means I am trying to dereference a null pointer. However, I cannot figure out where my code is dereferencing a null pointer. I am trying to set a char* (cstring) to a non-null value, but I get an access violation error. Here is the code:
void Data::setName(char const * const name)
{
if (this->name)
delete[] this->name;
this->name = new char[strlen(name) + 1]; // This is where my code breaks in debug mode
strcpy(this->name, name);
}
name is a char* variable that gets initialized to null. setName is being called by an overloaded assignment operator:
Data& Data::operator=(const Data& data2)
{
//if it is a self copy, don't do anything
if (this == &data2)
return *this;
else
{
setName(data2.name); // Here is the call to setName
return *this;
}
}
P.S. For the love of god please don't tell me I shouldn't be using cstrings! I know std::string is better, but this is for a homework assignment that requires cstrings.
Upvotes: 0
Views: 933
Reputation: 13313
If this is the line the code breaks:
this->name = new char[strlen(name) + 1];
then name
must be a null pointer, since nothing else is being dereferenced. name
is being dereferenced inside the strlen
function. Just print the variable value in your debugger and you will be sure.
Also, using same name of variable in the setter like this:
struct A
{
void set(int a){this->a = a;}
int a;
};
is not a good practice. Just use:
struct A
{
void set(int na){a = na;}
int a;
};
or
struct A
{
void set(int a){a_ = a;}
int a_;
};
Upvotes: 2