Help wanted

Ben Davis bnd25@cam.ac.uk
Mon Mar 17 16:53:00 GMT 2003


On Monday 17 March 2003 4:26 pm, Jane Liang wrote:
> Line 8      char *str = "0.12000, 0.0, 0.0";

This is a constant string, so it is stored in read-only memory.

> Line 13     *ptr = '\0';

You are now writing to read-only memory. Hence the crash.

You can fix your code by making 'str' an array instead:

   char str[] = "0.12000, 0.0, 0.0";

Then the string will be stored temporarily on the stack, which is writable. 
The array will be just the right size to accommodate the string.

When using GCC, I recommend you compile with -Wwrite-strings. String constants 
will then be given the 'const' qualifier, and you will get a warning if you 
don't use 'const' yourself where necessary:

   const char *str = "0.12000, 0.0, 0.0";

Ben



More information about the Gcc-help mailing list