Win said:
Hi All,
somebody told me this morning that the following is leagal.
char *a = "Hello wrold";
The memory is automatically allocated on the fly. Is this correct?
String literals may be placed in read-only memory, and it's undefined
behavior (UB) altering what *a points to. Hence, you should rather
use:
const char *a = "Hello wrold";
Note that, else the compiler might not catch this error:
$ cat -n main.c
1 #include <stdio.h>
2
3
4 int main(void)
5 {
6 char *a = "Hello";
7 const char *b = "Hello";
8
9 printf("%s %s\n", a, b);
10
11 a[0]='\0';
12 b[0]='\0';
13
14 return 0;
15 }
$ gcc -ansi -pedantic -W -Wall main.c
main.c: In function âmainâ:
main.c:12: error: assignment of read-only location
above, there was no warning about the UB at line 11!