gpt4 book ai didi

c - 反序列化错误

转载 作者:行者123 更新时间:2023-11-30 14:50:54 26 4
gpt4 key购买 nike

我正在实现一个简单的序列化和反序列化程序,但在反序列化期间出现错误,如段错误(核心转储)。

我正在使用“|”作为分隔符,检索数据。我认为我在将数据放回成员变量时犯了一个错误。

下一步我将尝试通过套接字发送数据

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

typedef struct Frame
{
char p[MAX];
char q[MAX];
char r[MAX];

}frame;

void serial(char [] , frame*);
void deserial(char [], frame*);


int main ()
{
char buffer [MAX];

int i = 0;

frame* packet1;
frame* packet2;

char temp[sizeof(frame)];

strcpy(packet1->p, "1234");
strcpy(packet1->q, "qwerty");
strcpy(packet1->r, "abcdef");
serial( temp, packet1);


deserial( temp, packet2);
return 0 ;
}

void serial ( char temp[], frame * packet1)
{
char* p = temp;
int len ;
int i=0;

len = strlen (packet1->p);
while ( i<len)
{
*p = packet1->p[i];
p++;
i++;
}
strcat(p,"|");
p++;
i = 0;
len = strlen (packet1->q);
while ( i<len)
{
*p = packet1->q[i];
p++;
i++;
}
strcat(p,"|");
p++;
i = 0;
len = strlen (packet1->r);
while ( i<len)
{
*p = packet1->r[i];
p++;
i++;
}
strcat(p,"|");
return;
}

void deserial ( char temp[], frame *packet2)
{
char *str = temp;
int i= 0 ;
char delimit[]="|";
printf("\n");
while (*str!='|')
{
printf ("%c\n", *str);
packet2->p[i] = *str; //error here
str++;
i++;
}
}

最佳答案

您对此代码有疑问

frame* packet1;   // This is a pointer and it is uninitialized
frame* packet2;

char temp[sizeof(frame)];

strcpy(packet1->p, "1234"); // Use of uninitialized pointer

你想做吗

frame packet1;
frame packet2;

char temp[sizeof(frame)];

strcpy(packet1.p, "1234");
...
serial( temp, &packet1);

进一步 - 当你这样做时

strcat(p,"|");

p 指向一些未初始化的内存,因此它不是字符串,并且 strcat 将(可能)失败。相反,请执行以下操作:

*p = '|';

关于c - 反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681567/

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