C++结构体中char*返回后丢失值的问题排查
C++新手求助:username和password值丢失问题
我是C++新手,搞不懂为什么代码里的username和password值会丢失。执行后id能正常输出,但username和password为空。
代码示例
Client *client = new Client(); char *authBuffer = new char[MAX_BUFFER_SIZE]; // buffer contains 234567|john|pwd4john bufferToClient(authBuffer, client); printf("id=%i username=%s password=%s\n", client->id, client->username, client->password); // output is: id=234567 username= password= // function void bufferToClient(char *buffer, Client *client) { memset(client, 0x00, CLIENT_STRUCT_SIZE); char *token = strtok(buffer, PIPE); // pipe | client->id = atoi(token); client->username = strtok(0, PIPE); client->password = strtok(0, PIPE); printf("%i\n", client->id); printf("%s\n", client->username); printf("%s\n", client->password); // everything is ok and prints out the values as expected // 234567 // john // pwd4john delete token; } // struct struct Client { unsigned int id; const char *username; const char *password; virtual ~Client() { delete username; delete password; } }; static const int CLIENT_STRUCT_SIZE = sizeof(Client);
尝试过的方法
用std::string(token).c_str()赋值:
client->username = std::string(token).c_str(); client->password = std::string(token).c_str();
输出结果:client id=234567 username=john password= ²,username正常但password乱码。
问题解决更新
后来调整了代码,现在能正常运行。修改内容包括:
- 移除
std::strings().c_str()转换 - 添加指向原指针的指针以正确
delete[]strtok指针(因为strtok会移动指针) - 移除结构体中的虚析构函数(有人指出这可能导致memset复制问题),并添加对username和password的delete操作
- 发现并修复了一个printf的bug(忘记添加变量导致输出错误值干扰判断)
我认为问题根源是std::strings().c_str()转换,移除后username和password就能正确返回了。
补充说明
这是有15年以上历史的旧代码,我正在做功能增强,所以没有使用最新的C++风格,但它的性能远优于Java21版本的同功能代码,就像布加迪对比80年代本田思域一样,果然越底层速度越快是有道理的。
内容的提问来源于stack exchange,提问作者defa0009
相关产品推荐
相关产品推荐

