1.现有结构体如下
typedef struct { //该结构体字节没有对齐
char terminalNumber[10]; //终端编码
uint8_t commandCode; //命令代码
uint8_t commandLength; //命令长度
uint8_t updateID[5]; //升级流水号
uint8_t updateChannel; //升级通道
uint16_t reserve1; //预留标识----通道参数
uint16_t reserve2; //下载和升级标识1
uint8_t updateDownFlag2; //下载和升级标识2
uint8_t fileType; //文件类型
uint32_t txID; //升级ID----TBOX节点号
uint32_t rxID; //应答ID----设备节点号
uint16_t downloadTime; //下载时间段,
uint16_t updateTime; //升级时间段
uint32_t fileSize; //下载的文件大小,单位为字节,max 4G
uint32_t filepathLength; //文件路径长度
uint32_t userPasswdLength; //用户名和密码长度
uint8_t crcType; //校验码类型
uint8_t crcLength; //校验码长度
char *filepath; //文件路径
char *userPasswd; //用户名和密码
uint8_t *crc; //校验码内容
}RecvUpdateInfo_t;
可以这样定义嘛
RecvUpdateInfo_t recvUpdateInfo;
为什么 memcpy(recvUpdateInfo->filepath, recv + 46, recvUpdateInfo->filepathLength); 会报段错误?
原因:
1.filepath 是一个 char* 指针,如果没有提前分配内存,直接 memcpy 会导致非法内存访问。
修复:
// 为 filepath 分配足够的内存(+1 用于 '\0' 终止符)
recvUpdateInfo->filepath = malloc(recvUpdateInfo->filepathLength + 1);
if (!recvUpdateInfo->filepath) {
perror("malloc failed");
return -1;
}
memcpy(recvUpdateInfo->filepath, recv + 46, recvUpdateInfo->filepathLength);
recvUpdateInfo->filepath[recvUpdateInfo->filepathLength] = '\0'; // 确保字符串终止
浙公网安备 33010602011771号