Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literals vs const char* in C

Tags:

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.

like image 655
Robin Avatar asked Jul 21 '10 20:07

Robin


People also ask

What is the difference between const char * and string?

string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.

Is a string literal a const char *?

In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time. As Christian points out, the const keyword was not originally a part of C.

Are string literals constant in C?

They are not const in C, but are in C++. They aren't generally writable as noted by others, but they don't behave as constants. There are some weird things you can't do, like 'case "abc"[2]:' in C, but you can in C++ where string literals are constant.

What is a const char * in C?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.


1 Answers

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

like image 113
Hans Passant Avatar answered Oct 24 '22 20:10

Hans Passant