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. Advertising

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

  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. Advertising

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:
    0
    Views:
    777
    Mladen Adamovic
    Dec 4, 2003
  2. Mladen Adamovic
    Replies:
    3
    Views:
    14,780
    Mladen Adamovic
    Dec 5, 2003
  3. =?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,820
    =?Utf-8?B?UmFqZXNoIHNvbmk=?=
    May 4, 2006
  4. Mara Guida

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

    Mara Guida, Sep 2, 2009, in forum: C Programming
    Replies:
    3
    Views:
    524
    David RF
    Sep 3, 2009
  5. Tom
    Replies:
    3
    Views:
    236
    salsablr
    Dec 20, 2004
Loading...

Share This Page