gpt4 book ai didi

c - snprintf 错误。 sizeof 的参数与目标相同

转载 作者:太空狗 更新时间:2023-10-29 16:38:12 24 4
gpt4 key购买 nike

gcc 4.8 在构建时给我一个错误

#include <string.h>
#include <stdio.h>

static inline void toto(char str[3])
{
snprintf(str, sizeof(str), "XX");
}

int main(){
char str[3];
toto(str);
return 0;
}

这是gcc错误

错误:“snprintf”调用中“sizeof”的参数与目标表达式相同;您是要提供明确的长度吗?

注意:我使用 -Wall -Werror 标志将警告转换为错误。

There is something similar here在评论中,有人回答了这个问题

“对于固定长度的缓冲区,我通常使用 strncpy(dest, src, sizeof(dest)); dest[sizeof(dest)-1] = '\0'; 这保证了 NULL 终止并且只是更少比 snprintf 更麻烦,更不用说很多人使用 snprintf(dest, sizeof(dest), src); 代替,并且当他们的程序任意崩溃时感到非常惊讶。”

但这是错误的:gcc 4.8 说

“错误:‘strncpy’调用中‘sizeof’的参数与目标表达式相同;您是要提供明确的长度吗?[-Werror=sizeof-pointer-memaccess]”

in gcc 4.8 documentation, they are talking about this issue :他们说:

-Wall 的行为已更改,现在包含新的警告标志 -Wsizeof-pointer-memaccess。这可能会导致在使用以前版本的 GCC 干净编译的代码中出现新警告。

例如,

include string.h

struct A { };

int main(void)
{
A obj;
A* p1 = &obj;
A p2[10];

memset(p1, 0, sizeof(p1)); // error
memset(p1, 0, sizeof(*p1)); // ok, dereferenced
memset(p2, 0, sizeof(p2)); // ok, array
return 0;
}

提供以下诊断:警告:“void memset(void*, int, size_t)”调用中“sizeof”的参数与目标表达式相同;你的意思是取消引用它吗? [-Wsizeof-pointer-memaccess] memset(p1, 0, sizeof(p1));//错误 ^尽管这些警告不会导致编译失败,但通常 -Wall 与 -Werror 结合使用,结果,新的警告变成了新的错误。要修复,请重新编写以使用 memcpy 或取消引用有问题的 memset 调用中的最后一个参数。*

好吧,在他们的例子中,很明显代码是错误的,但在我的例子中,使用 snprintf/strncpy,我不明白为什么,我认为这是 gcc 的误报错误。对吧?

谢谢你的帮助

最佳答案

当您将数组传递给函数时,它会衰减为指向第一个元素的指针。所以你有什么

static inline void toto(char str[3]) {..}

不是数组而是指针。

因此,gcc 正确地警告。

无论您是否在函数参数中指定大小都没有关系,因为:

static inline void toto(char str[3])

static inline void toto(char str[])

static inline void toto(char *str)

都是等价的。

阅读此处:what is array decaying?

关于c - snprintf 错误。 sizeof 的参数与目标相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202368/

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