c - 指针上的 sizeof

标签 c pointers arguments sizeof

当我的编译器发出警告时,我正在尝试为我的 HTC 手机编译内核:

static ssize_t mipi_dsi_3d_barrier_read(struct device *dev,
                struct device_attribute *attr,
                char *buf)
{
    return snprintf((char *)buf, sizeof(buf), "%u\n", barrier_mode);
}

带有消息

warning: argument to 'sizeof' in 'snprintf' call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess] error, forbidden warning: mipi_novatek.c:524

我已经修复了一些这样的问题,因为我知道 sizeof(buf) 没有意义,因为 buf 作为参数传递,因此编译器不知道缓冲区大小 - 即使您碰巧传递静态缓冲区。

问题是,在修复了一些这样的问题之后,我想知道我是否遗漏了一些东西。我从 github 存储库下载了内核,其中包含来自“原始”htc 内核的相当多的提交,并且我可以在两者中找到这些错误,因此对于其他人来说它肯定编译得很好。

我是不是漏掉了或者做错了什么?我使用 ubuntu 存储库中的 arm-none-eabi-gcc 4.8.2,而不是按照建议从 android.googlesource.com 下载。但无论编译器如何,这都是一个错误,不是吗?您不应该将缓冲区大小作为额外参数传递吗?

编辑同一内核中的另一个这样的例子......

struct msm_adsp_module *module;

...

if (!strncmp(module->name, "QCAMTASK", sizeof(module->name)))
    module_irq_cnt[1]++;
else if(!strncmp(module->name, "VFETASK", sizeof(module->name)))
    module_irq_cnt[2]++;
else if(!strncmp(module->name, "VIDEOENCTASK", sizeof(module->name)))
    module_irq_cnt[3]++;

哪里

struct msm_adsp_module {
    struct mutex lock;
    const char *name;
    ...

最佳答案

哎呀,抱歉,刚刚从另一个线程中错过了它,这使得问题非常清楚

snprintf error. argument to sizeof is the same as destination

in gcc 4.8 documentation, they are talking about this issue: they say:

The behavior of -Wall has changed and now includes the new warning flag -Wsizeof-pointer-memaccess. This may result in new warnings in code that compiled cleanly with previous versions of GCC.

所以我猜这肯定是一个错误,而其他人只是碰巧使用旧的编译器。我简直不敢相信生产内核上有这样的代码......

关于c - 指针上的 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095901/

相关文章:

c - 从 time_t 中减去 char 指针

arguments - Swift:通过引用传递原语的用例是什么

c - 在下面的场景中我是服务器还是客户端?

c - 为什么我们必须分别指定每个形式参数的数据类型?

c++ - 在 C/C++ 中分配数组的数组

c - (段错误)读取变量时出错,无法读取地址 X 处的变量

c - 在 c 中编写 oo Lua 接口(interface)的最佳方法?

c - 小数点精度丢失,可能是格式问题? C程序设计语言

bash - 我如何在 Bash 中解析命令行参数?

mysql - 获取存储过程的参数数量