Richard Dawe rich at
Sat May 19 13:17:31 BST 2007


David Cantrell wrote:
> On Sun, May 13, 2007 at 09:35:22AM +0100, Andy Wardley wrote:
>> It's also worth noting that this is Not Allowed:
>>    char *string = "this is a test",
>>    strcpy(*string, "new string");
>> You shouldn't update static strings lest you crave a Bus Error
>> or Segmentation Fault.
> Obviously doing that when "new string" is longer than "this is a test"
> is a no-no, but what's wrong with it in the specific example you gave?

First argument to strcpy() should be a char * pointer. Code above is
passing a char. So:

  char *string = "this is a test";
  strcpy(string, "new string");

>> Caveat: I am not a C programmer (well, not that often)
> Nor am I (that often).
> Oh, I figgered out what's wrong with it.  Memory allocated read-only for
> paranoid reasons?

In C++ "this is a test" is a constant string, and the conversion from
string constant to char * is deprecated. See the help for gcc's
-Wwrite-strings option in the info manual:

  info gcc invoking warn

There's also string constant merging. If you had multiple instances of
"this is a test" in your program, the C compiler might have merged them
into one instance. Which could surprise you.

Bye, Rich =]

Richard Dawe [ ]

"You just amass stuff while you are alive. It's like stuff washed up
 on a beach somewhere, and that somewhere is you." -- Damien Hirst

More information about the mailing list