使用字符串访问冲突写入位置0xcccccccc

Azi*_*Mat 0 c++ string pointers visual-c++

在过去的4天里,我一直坚持这个错误:

Unhandled exception at 0x77c415de in ls_client_app.exe: 
0xC0000005: Access violation reading location 0xcccccccc.
Run Code Online (Sandbox Code Playgroud)

这是代码:

typedef struct client {
    string  ID;
    // some other strings
} client;

typedef struct client_card {
    client CLIENT;
    client_card * next;
} client_card;

typedef client_card * ls_client;
Run Code Online (Sandbox Code Playgroud)

这是add_client函数:

int add_client(ls_client &LS_CLIENT) {

    client NEW_CLIENT;
    ls_client NEW_CLIENT_CARD = (ls_client) malloc (sizeof(client_card));

    cout << "CLIENT ID: " <<endl;
    cin  >>  NEW_CLIENT.ID;

    NEW_CLIENT_CARD->next    =  NULL;
    NEW_CLIENT_CARD->CLIENT  =  &NEW_CLIENT;

    while (LS_CLIENT != NULL) {
        LS_CLIENT = LS_CLIENT->next;
    }
    LS_CLIENT = NEW_CLIENT_CARD;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是主要的:

int main() {
    ls_client LS_CLIENT = (ls_client) malloc (sizeof(client_card));
    LS_CLIENT = NULL;
    add_client(LS_CLIENT);

    // Error in this line !
    cout << LS_CLIENT->CLIENT->ID <<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

带我去streambuf文件第二行!

else if (_Traits::eq_int_type(_Traits::eof(),
    overflow(_Traits::to_int_type(*_Ptr))))
    break;  // single character put failed, quit
else
//...
Run Code Online (Sandbox Code Playgroud)

请有人帮助我,我将不胜感激!
谢谢你的尝试!!

Xyz*_*yzk 7

ls_client LS_CLIENT = (ls_client) malloc (sizeof(client_card)); LS_CLIENT = NULL;

您正在创建客户端,然后将其设置为NULL.您的错误是访问冲突错误.基本上,您正在尝试处理NULL指针.交换那些线,它应该没问题.

编辑:有人编辑了您的代码,使其不再包含此错误.如果这是你的方式,请忽略这个答案(抱歉混淆答案与评论).

  • @AzizMat先生,在充分尊重的情况下,您的代码被错误地填充了*.这里确定的只是其中之一.你看到你怎么没有将刚刚分配的LS_CLIENT的`next`成员指针设置为NULL?它是不确定的,在这种情况下,显然不应该是NULL.然后是add_client中的错误,将局部变量的地址推送到链接列表中以便访问范围; 也是未定义的行为.您正在使用`malloc()`来分配C++对象,不会触发构造函数,并且您的std :: string成员是不确定的,但更多的是未定义的行为. (3认同)
  • 它仍然存在于`main()`(无论如何都是这个评论). (2认同)