Q: Why does this code:
char *p = "hello, world!"; p[0] = 'H';crash?
A: String constants are in fact constant. The compiler may place them in nonwritable storage, and it is therefore not safe to modify them. When you need writable strings, you must allocate writable memory for them, either by declaring an array, or by calling malloc. Try
char a[] = "hello, world!";
By the same argument, a typical invocation of the old Unix mktemp routine
char *tmpfile = mktemp("/tmp/tmpXXXXXX");is nonportable; the proper usage is
char tmpfile[] = "/tmp/tmpXXXXXX"; mktemp(tmpfile);
See also question 1.32.
References:
ISO Sec. 6.1.4
H&S Sec. 2.7.4 pp. 31-2