Thread: strange behavior

  1. #1
    Registered User
    Join Date
    Oct 2005
    Location
    Hyderabad, India
    Posts
    33

    strange behavior

    Any reasons for the below mentioned behavior?? i use gcc .
    I think both should have run sucessfully.

    Code:
    /* this gives segmentation fault */
    #include <stdio.h>
    main(){
        char* a = "abcd";
        a[1] = '\0';
    }
    Code:
    /* this doesn't give segmentation fault */
    #include <stdio.h>
    main(){
        char a[] = "abcd";
        a[1] = '\0';
    }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    String literals are usually stored in read-only memory. When you do char *a = "abcd"; you're creating a pointer that points to a string that resides in read-only memory.

    When you do char a[] = "abcd"; you're creating an array that the string "abcd" is copied into. So when you do a[1] = '\0'; later you're modifying the array instead of the string in read-only memory.

    Trying to modify the read-only memory is what's giving you the segmentation fault.

    You can try giving gcc the -fwritable-strings option to make the pointer one work, but it's better to just avoid the practice altogether.
    Code:
    itsme@itsme:~/C$ cat segfault.c
    #include <stdio.h>
    
    int main(void)
    {
      char *a = "foo";
    
      a[1] = '\0';
      return 0;
    }
    itsme@itsme:~/C$ gcc -Wall segfault.c -o segfault
    itsme@itsme:~/C$ ./segfault
    Segmentation fault (core dumped)
    itsme@itsme:~/C$ gcc -Wall -fwritable-strings segfault.c -o segfault
    cc1: note: -fwritable-strings is deprecated; see documentation for details
    itsme@itsme:~/C$ ./segfault
    itsme@itsme:~/C$
    You can see that the -fwritable-strings prevented the segmentation fault, but it's a deprecated feature that will probably go away eventually.
    Last edited by itsme86; 10-17-2005 at 12:10 PM.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  2. strange std::map behavior
    By manav in forum C++ Programming
    Replies: 63
    Last Post: 04-11-2008, 08:00 AM
  3. C++ list Strange Behavior
    By yongzai in forum C++ Programming
    Replies: 19
    Last Post: 12-29-2006, 02:56 AM
  4. Strange behavior of Strings
    By shyam168 in forum C Programming
    Replies: 9
    Last Post: 03-27-2006, 07:41 AM
  5. Strange behavior with CDateTimeCtrl
    By DonFiasco in forum Windows Programming
    Replies: 2
    Last Post: 12-19-2004, 02:54 PM