字符串字面VS用C为const char * [英] String literals vs const char* in C
问题描述
为什么不ANSI C编译器标志函数调用使用字符串参数的其中correponding参数没有一个const修饰词?例如,下面的code可以通过尝试写入只读存储器产生异常。
Why don't ANSI C compilers flag the use of a string literal argument in a function call in which the correponding parameter does not have a const qualifier? For example, the following code could generate an exception by trying to write to read only memory.
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会产生编译器警告。
This situation could be identified at compile time but VS2010 and gcc don't appear to do so. Calling somefunc with a const char* argument will generate a compiler warning.
推荐答案
GCC:使用标记 -Wwrite串
PS。 GCC手册解释了为什么这不是-Wall的一部分。总之,一如既往,你应该找到适合你的特殊需要和编码风格-W标志的组合。例如,在最近的一个项目我已经使用了这样的事情: -Werror -Wall -Wextra -Wformat = 2 -Winit自-Wswitch-枚举-Wstrict走样= 2 -Wundef -Wshadow -Wpointer -arith -Wbad功能铸-Wcast-QUAL -Wcast对准-Wwrite弦-Wstrict的原型-WOLD式高清-Wmissing的原型-Wmissing-声明-Wredundant-decls -Wnested-实习医生-Winline -Wdisabled -optimization -Wunused-宏-Wno-未使用
PS. gcc manual explains why this isn't part of -Wall. Anyway, as always, you should find a combination of -W flags that suits your particular needs and coding style. For example, in a recent project I have used something like this: -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
这篇关于字符串字面VS用C为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!