简体   繁体   English

访问冲突读取位置0x00000000 cstrings

[英]Access violation reading location 0x00000000 cstrings

From reading other stackoverflow questions I am aware that this error means I am trying to dereference a null pointer. 通过阅读其他stackoverflow问题,我知道此错误意味着我正在尝试取消引用空指针。 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. 我试图将char *(cstring)设置为非null值,但是出现访问冲突错误。 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. name是一个char *变量,已初始化为null。 setName is being called by an overloaded assignment operator: 重载的赋值运算符正在调用setName:

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;
    }
}

PS For the love of god please don't tell me I shouldn't be using cstrings! PS对于上帝的爱,请不要告诉我,我不应该使用cstrings! I know std::string is better, but this is for a homework assignment that requires cstrings. 我知道std :: string更好,但这是针对需要cstrings的作业的。

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必须是一个空指针,因为没有其他东西被取消引用了 name is being dereferenced inside the strlen function. namestrlen函数中被取消引用。 Just print the variable value in your debugger and you will be sure. 只需在调试器中打印变量值,就可以确定。


Also, using same name of variable in the setter like this: 同样,在setter中使用相同的变量名称,如下所示:

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_;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM