This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug c/35384] Variables declared as 'static char * avar = "some string";' cannot be modified



------- Comment #3 from Quinlan at ACM dot org  2008-02-26 20:10 -------
I appreciate your answer, however shouldn't this declaration:
  static char * avar = "some string";
be identical to this:
  static char * avar = NULL;
  avar = "some string";

Yet when the application executes:
  avar[4] = '_';
with the first declaration I get SIGSEGV while with the second declaration the
fifth character is changed. Why? Does the behavior of the second declaration
result from a bug and if so should I not be using this approach as it is likely
to stop working with the next gcc upgrade? In both instance avar is a pointer
to a constant string!

Note that I encountered this problem in code that was written about 10 years
ago, and that works with early gcc versions and with Microsoft's compilers.

To avoid making a change to a constant variable do I really need to replace a
simple line of code like: 
  static char * avar = NULL;
with this much more complicated approach:
  static char * orig_var = "some string";
  static char * avar = NULL;
  if(avar == NULL) { avar = (char *)calloc(12,1); memcpy(avar,orig_var,12);}
  .... // Now I can safely modify characters in avar
  free(avar); // Sometime before the application exits


-- 

Quinlan at ACM dot org changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |UNCONFIRMED
         Resolution|INVALID                     |


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35384


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]