c - Netlink 接收缓冲区对齐
问题描述
PVS-Studio,一个静态分析器,报告说nh = (struct nlmsghdr *) buf
,
指针“buf”被转换为更严格对齐的指针类型。
我认为警告是正确的。这是一个严重的问题吗?代码需要在各种架构上可移植。我怎样才能解决这个问题?
我知道一些方法:
还有其他选择吗?
下面的代码取自netlink 手册页。
int len;
char buf[8192]; /* 8192 to avoid message truncation on
platforms with page size > 4096 */
struct iovec iov = { buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;
msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);
for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len);
nh = NLMSG_NEXT (nh, len)) {
/* The end of multipart message */
if (nh->nlmsg_type == NLMSG_DONE)
return;
if (nh->nlmsg_type == NLMSG_ERROR)
/* Do some error handling */
...
/* Continue with parsing payload */
...
}
谢谢。
解决方案
用一个已分配的指针struct nlmsghdr
而不是一个指针不是更好char buf[8192]
吗?
例如:
int len;
struct nlmsghdr buf;
struct iovec iov = { &buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;
msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);
for (nh = &buf; NLMSG_OK (nh, len);
nh = NLMSG_NEXT (nh, len)) {
/* The end of multipart message */
if (nh->nlmsg_type == NLMSG_DONE)
return;
if (nh->nlmsg_type == NLMSG_ERROR)
/* Do some error handling */
...
/* Continue with parsing payload */
...
}
推荐阅读
- powershell - 如何获取 Hyper-V 主机最近一小时的 CPU 使用率?
- .net - 使 ClickOnce 完全信任应用程序“绿色”
- azure - UserSecretsId 阻止将 F# ASP.NET Core 应用程序部署到 Azure 应用程序服务
- cordova-plugins - Crodova vk 插件不起作用[无法从清单文件中读取包名]
- python - Heroku python 应用程序抛出错误 - KeyError: 'pip._vendor.urllib3.util.queue'
- reporting-services - rdl一页可以显示多少行
- javascript - 如何使用 JavaScript 从 API 获取 XML 响应?
- db2 - BLOB 到字符串的转换 - DB2
- javascript - 绘制到画布或用作图像源时缺少 SVG 图像和图案
- python - 如何在python中继承类(odoo框架控制器)