recvUpdateInfo->filepath = (char *)malloc(recvUpdateInfo->filepathLength + 1);
memcpy(recvUpdateInfo->filepath, recv + 44, recvUpdateInfo->filepathLength);
我这样写对吗?
改进建议:
// 1. 首先检查长度是否合理
if (recvUpdateInfo->filepathLength <= 0 || recvUpdateInfo->filepathLength > MAX_PATH_LENGTH) {
// 处理错误情况
return -1;
}
// 2. 分配内存并检查是否成功
recvUpdateInfo->filepath = (char *)malloc(recvUpdateInfo->filepathLength + 1);
if (recvUpdateInfo->filepath == NULL) {
// 处理内存分配失败
return -2;
}
// 3. 拷贝数据
memcpy(recvUpdateInfo->filepath, recv + 44, recvUpdateInfo->filepathLength);
// 4. 添加字符串终止符
recvUpdateInfo->filepath[recvUpdateInfo->filepathLength] = '\0';
浙公网安备 33010602011771号