Writeability of strings

William E. Davidsen Jr davidsen at steinmetz.ge.com
Tue Dec 20 04:04:23 AEST 1988


In article <1316 at papaya.bbn.com> rsalz at bbn.com (Rich Salz) writes:
| Simple question.  Which is legal and/or "safer":
| 
| 	char *foo = "/tmp/xxxxxx";
| 	(void)mktemp(foo);
| 
| 	char *foo = mktemp("/tmp/xxxxxx");

  These will fail if you are not able to modify the value of a constant
string in memory.

| 	char foo[] = "/tmp/xxxxxx";
| 	(void)mktemp(foo);

  This may fail if used more than once (I got badly burned by this). The
behavior of mktmp is not predictable if the input string doesn't contain
the xxxxxx string. Some will fail, some will do nothing, and some will
append a six digit number to the end of the string. This last behavior,
in a system in which strings are writable, will cause the string to
become six chars longer with each call, until it trashes something and
the program dies. Some compilers also want to see { braces } around
array init, so 'char foo[] = {"string"};' is more portable. I learned
that the hard way, too.

| 	#define TEMPNAME "/tmp/xxxxxx";
| 	char foo[sizeof TEMPNAME];
| 	(void)mktemp(strcpy(foo, TEMPNAME));

  This should work in ANSI, UNIX or MS-DOS C environments (or any other
I can think of). You are starting with a fresh copy of the string each
time, in a variable.

-- 
	bill davidsen		(wedu at ge-crd.arpa)
  {uunet | philabs}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me



More information about the Comp.std.c mailing list