pointer error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • questionit
    Contributor
    • Feb 2007
    • 553

    pointer error

    Hi experts

    Why i get run-time error with this:

    char *temp ="string";

    temp[2] = '\0'; // < get errror here?

    Memory address is not being touched but only a value which resides on the momory is being altered, there should not be any problem doing this?

    Please explain
    Thanks
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    temp is pointing to a string constant. String constants on some platforms are just that, constant. Trying to alter them causes a memory access exception.

    In general it is best to avoid altering a string constant, if you need to modify it copy it to a variable or allocated data and alter the copy.

    Comment

    • nmadct
      Recognized Expert New Member
      • Jan 2007
      • 83

      #3
      Originally posted by questionit
      Hi experts

      Why i get run-time error with this:

      char *temp ="string";

      temp[2] = '\0'; // < get errror here?

      Memory address is not being touched but only a value which resides on the memory is being altered, there should not be any problem doing this?
      A string literal like "string" is stored in non-writable memory (with most C compilers). So, the pointer temp is pointing to a memory location that you're not allowed to write to. When you try to write to it anyway, it causes a runtime error. There are a couple of ways you can get around this problem:

      char temp[] = "string"; // works if temp is a global variable

      char temp[7]; // remember to allocate an extra byte for the terminating null!
      strcpy(temp, "string");

      Either one of these approaches gives you a buffer in writable memory that is filled with the value "string".

      Comment

      Working...