gpt4 book ai didi

C - 将结构序列化为 char* 会更改原始数据

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:21 26 4
gpt4 key购买 nike

正在关注 this问题,我决定序列化一些我需要通过 TCP/IP 连接发送的数据。

数据非常简单:

typedef struct whiteboard {
int palladium, platine, zirconium, erbium, astate, californium;
} sharedData;

我的序列化函数也很简单:

void serializeWhiteboard (sharedData* message, char** packet) {
int* r = (int*) packet;
*r = (int)VALUE_FROM_ENUM; // just some enum to get the type of message sent
r++;
char* q = (char*) r;
*q = '/'; q++; // delimitors for parsing
*q = '/'; q++; // the message on the other end
int* p = (int*) q;
*p = message->palladium; p++;
*p = message->platine; p++;
*p = message->zirconium; p++;
*p = message->erbium; p++;
*p = message->astate; p++;
*p = message->californium; p++;
return;
}

在我的调用程序中,我有以下代码:

int main() {
sharedData data = {0};
// define the data values ...
char* dest = malloc(sizeof(int) + 2*sizeof(char) + 6*sizeof(int));
serialiseWhiteboard(&data, &dest);
// And here, the first two fields of 'data' have changed
// as if by magic, since I do not touch the fields in
// serializeWhiteboard() .
return 0;
}

我一辈子都弄不明白为什么当我只从数据中读取值时,前两个数据字段会发生变化。然而,通过一些打印值,我能够将其追踪到 serializeWhiteboard() 中的倒数第二行,就在 return; 之前,这并没有有任何意义。在调用 return 之前数据都很好。

有没有人遇到过这样的问题?

最佳答案

您有 char** 数据包,它是指向某些字符的指针。

然后您将其视为 int *,它是指向某些整数的指针。

然后您覆盖第一个 int - 所以您写入的是“dest”本身,而不是它指向的内容。因为在那之后你写了更多,你正在破坏堆栈。

关于C - 将结构序列化为 char* 会更改原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53688450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com