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

时间:2013-04-03 20:30:50

标签: c++ string visual-c++ pointers

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

Unhandled exception at 0x77c415de in ls_client_app.exe: 
0xC0000005: Access violation reading location 0xcccccccc.

以下是代码:

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;

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

这是主要的:

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

带我到streambuf文件第二行!

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

任何人都可以帮助我,我将不胜感激!
谢谢你的尝试!!

1 个答案:

答案 0 :(得分:7)

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

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

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