字符串文字与C中的const char *

时间:2010-07-21 20:12:41

标签: c

为什么ANSI C编译器不会在函数调用中标记字符串文字参数的使用,其中相关参数没有const限定符?例如,以下代码可以通过尝试写入只读内存来生成异常。

void somefunc(char buffer[10]);

void somefunc(char buffer[10]) {
    int i;

    for (i = 0;   i < 10;   i++)
       buffer[i] = 0;
}

int main(int argc, char **argv) {

    somefunc("Literal");
    return 0;
}

这种情况可以在编译时确定,但VS2010和gcc似乎没有这样做。使用const char *参数调用somefunc将生成编译器警告。

5 个答案:

答案 0 :(得分:16)

这是K&amp; R的遗产。修复它会破坏一百万个程序。

答案 1 :(得分:11)

gcc:使用标记-Wwrite-strings

PS。 gcc手册解释了为什么这不是-Wall的一部分。无论如何,一如既往,您应该找到适合您特定需求和编码风格的-W标志组合。例如,在最近的一个项目中,我使用过这样的东西:-Werror -Wall -Wextra -Wformat=2 -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused

答案 2 :(得分:7)

Hans Passant说的话。 const是作为1989年ANSI标准的一部分添加的,因此之前的任何东西都没有const。

答案 3 :(得分:6)

字符串文字在C中不是const;在C ++中它们是。

编辑:清除对我评论的任何疑惑,我指的是类型,而不是实际更改它们的能力。

答案 4 :(得分:4)

如果使用-Wwrite-string,GNU编译器(以及Intel C编译器,iirc)将发出警告:

$ gcc -Wall -Wwrite-strings -o foo /tmp/foo.c
/tmp/foo.c: In function 'main':
/tmp/foo.c:12: warning: passing argument 1 of 'somefunc' discards qualifiers from pointer target type
/tmp/foo.c:3: note: expected 'char *' but argument is of type 'const char *'

关于VS2010,我帮不了你。

相关问题