首页 文章

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

提问于
浏览
0

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

我不能为我的生活弄清楚为什么当我从中读取值时,前两个数据字段会发生变化 . 然而,通过一些打印值,我能够在 return; 之前跟踪它到倒数第二行,就在 return; 之前,这没有任何意义 . 数据很好,直到调用 return 之前 .

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

1 回答

  • 3

    你有 char** packet 这是指向某些字符的指针 .

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

    然后你覆盖第一个 int - 所以你're writing into ' dest ' itself and not what it points to. And since you write more after that, you'破坏了堆栈 .

相关问题