[OCLUG-devel] strcpy segmentation faults

Morgan Simpson msimpson at braysimpson.com
Fri Jun 24 12:02:42 PDT 2005


On Jun 23, 2005, at 11:01 PM, Doug Jolley wrote:

> Do you see a difference between:
>        char myVar[] = "My dog has fleas.";
> and
>        const myVar char[] = "My dog has fleas.";

In the second case, the compiler will (should) issue an error if you 
use "myVar" as an lvalue in an expression. A bigger issue arises with:

   char *myVar  = "My dog has fleas."; // example 1
   char myVar[] = "My dog has fleas."; // example 2

If you attempt to modify the string in example 1, you should get a 
segmentation fault because the GCC compiler stored the string in a 
read-only segment of memory. This problem does not occur with example 2 
as the string resides in a writable segment of memory. If you want to 
safely modify the string in example 1, you need to use the GCC flag 
-fwritable-strings.

Hope this helps.

Regards,

Morgan Simpson
Bray, Simpson and Associates, Inc.



More information about the OCLUG-devel mailing list