C Interview Questions and Answers

 

Why does this code crash?

Why does this code:



char *p = "hello, world!";



p[0] = 'H';



crash?





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);

Posted by:Richards