prev up next   top/contents search

comp.lang.c FAQ list · Question 16.6

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


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North