开发者

String literals vs const char* in C

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;
}

This situation could be identified at compile time but VS2010 and gcc don't appear to do so. Calling somefunc with a 开发者_JAVA百科const char* argument will generate a compiler warning.


It is a K&R legacy. Fixing it would break a million programs.


gcc: Use the flag -Wwrite-strings

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


What Hans Passant said. const was added as part of the ANSI standard on 1989, so anything from before that didn't have const.


string literals are not const in C; in C++ they are.

edit: to clear up any confusion about my comment, I am referring to the type, not the ability to actually change them.


The GNU compiler (and the Intel C compiler as well, iirc) will emit a warning, if -Wwrite-string is used:

$ 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 *'

Concerning VS2010, I can't help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜