String/Array Question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matthew Alton

    #1

    String/Array Question

    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.
  • Irrwahn Grausewitz

    #2
    Re: String/Array Question

    malton@myit.biz (Matthew Alton) wrote:[color=blue]
    >Why does this code generate a SIGSEGV?[/color]
    [color=blue]
    > char *s = "ABC";
    > s[1] = 'X';[/color]

    http://www.eskimo.com/~scs/C-faq/top.html Question 1.32

    Regards
    --
    Irrwahn Grausewitz (irrwahn33@free net.de)
    welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
    clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
    clc OT guide : http://benpfaff.org/writings/clc/off-topic.html

    Comment

    • Barry Schwarz

      #3
      Re: String/Array Question

      On 24 Apr 2004 17:03:01 -0700, malton@myit.biz (Matthew Alton) wrote:
      [color=blue]
      >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);
      >}
      >[/color]

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

      Comment

      Working...