Robin
Robin

Reputation: 103

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 const char* argument will generate a compiler warning.

Upvotes: 10

Views: 2902

Answers (5)

frankc
frankc

Reputation: 11473

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.

Upvotes: 6

user355252
user355252

Reputation:

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.

Upvotes: 4

Jukka Suomela
Jukka Suomela

Reputation: 12338

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

Upvotes: 12

ninjalj
ninjalj

Reputation: 43688

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

Upvotes: 7

Hans Passant
Hans Passant

Reputation: 941227

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

Upvotes: 16

Related Questions