String/Array Question

Discussion in 'C Programming' started by Matthew Alton, Apr 25, 2004.

  1. Why does this code generate a SIGSEGV?

    #include <stdio.h>

    int
    main(void)
    {
    char *s = "ABC";

    s[1] = 'X';

    return(0);
    }

    while this does not:

    #include <stdio.h>

    int
    main(void)
    {
    char s[] = "ABC";

    s[1] = 'X';

    return(0);
    }


    The *s declaration followed by a reference to s[-1] is used in
    FreeBSD's strsep(3). It dumps core on Red Hat Linux 7.x and NetBSD
    1.6.1.
     
    Matthew Alton, Apr 25, 2004
    #1
    1. Advertisements

  2. Irrwahn Grausewitz, Apr 25, 2004
    #2
    1. Advertisements

  3. On 24 Apr 2004 17:03:01 -0700, (Matthew Alton) wrote:

    >Why does this code generate a SIGSEGV?
    >
    >#include <stdio.h>
    >
    >int
    >main(void)
    >{
    > char *s = "ABC";
    >
    > s[1] = 'X';
    >
    > return(0);
    >}
    >
    >while this does not:
    >
    >#include <stdio.h>
    >
    >int
    >main(void)
    >{
    > char s[] = "ABC";
    >
    > s[1] = 'X';
    >
    > return(0);
    >}
    >


    Because your compiler is doing it best to comply with the requirement
    that a string literal be non-modifiable. See the faq at
    http://www.eskimo.com/~scs/C-faq/top.html. The answer to your
    question is near the beginning but you should read the whole thing.


    <<Remove the del for email>>
     
    Barry Schwarz, Apr 25, 2004
    #3
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mladen Adamovic
    Replies:
    3
    Views:
    15,348
    Mladen Adamovic
    Dec 5, 2003
  2. =?Utf-8?B?UmFqZXNoIHNvbmk=?=

    'System.String[]' from its string representation 'String[] Array'

    =?Utf-8?B?UmFqZXNoIHNvbmk=?=, May 4, 2006, in forum: ASP .Net
    Replies:
    0
    Views:
    1,982
    =?Utf-8?B?UmFqZXNoIHNvbmk=?=
    May 4, 2006
  3. Replies:
    7
    Views:
    851
  4. sigi
    Replies:
    4
    Views:
    700
  5. Replies:
    2
    Views:
    407
    James Kanze
    Dec 11, 2007
  6. Mara Guida

    const and array of array (of array ...)

    Mara Guida, Sep 2, 2009, in forum: C Programming
    Replies:
    3
    Views:
    822
    David RF
    Sep 3, 2009
  7. Tom
    Replies:
    3
    Views:
    403
    salsablr
    Dec 20, 2004
  8. Tuan  Bui
    Replies:
    14
    Views:
    785
    it_says_BALLS_on_your forehead
    Jul 29, 2005
Loading...