question for char point.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Franklin Li

    #1

    question for char point.

    Hi all,

    I have one simple program:
    #define __EXTENSIONS__
    #include <stdio.h>
    #include <string.h>

    int main() {
    char *buf="5/90/45";
    char *token;
    char *lasts;

    printf("tokeniz ing \"%s\" with strtok():\n", buf);
    if ((token = strtok(buf, "/")) != NULL) {
    printf("token = "%s\"\n", token);
    while ((token = strtok(NULL, "/")) != NULL) {
    printf("token = \"%s\"\n", token);
    }
    }
    }

    When I compile it using CC and got one Warning: String literal converted to
    char* in assignment.
    When I run it and got Segmentation Fault(coredump) .

    Then I changed defination as below:
    char str[] = "5/90/45";
    char *buf = str;

    Then this is no warning and I can get the correct result.

    Could you give me the reason?

    I think I can use char *point = "string" directly.

    Thansk.

    Franklin


  • baumann@pan

    #2
    Re: question for char point.


    in msdn i got

    char *strtok( char *strToken, const char *strDelimit );
    wchar_t *wcstok( wchar_t *strToken, const wchar_t *strDelimit );
    Parameters

    strToken
    String containing token(s)
    strDelimit
    Set of delimiter characters
    Libraries

    All versions of the C run-time libraries.



    All of these functions return a pointer to the next token found in
    strToken. They return NULL when no more tokens are found. Each call
    modifies strToken

    ~~~~~~~~~~~~~~~ ~~~~

    ~~~~~~~~~~~~~~~ ~~~

    by substituting a NULL character for each delimiter that is
    encountered.
    ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~
    ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~

    now you see strtok will modify the content of the first argument.

    but your code write

    char * buf = "";

    which you can not modify its content.

    use char buf[] = "" is ok,
    because buf 's cotent become modifiable.

    baumann@pan

    Franklin Li wrote:[color=blue]
    > Hi all,
    >
    > I have one simple program:
    > #define __EXTENSIONS__
    > #include <stdio.h>
    > #include <string.h>
    >
    > int main() {
    > char *buf="5/90/45";
    > char *token;
    > char *lasts;
    >
    > printf("tokeniz ing \"%s\" with strtok():\n", buf);
    > if ((token = strtok(buf, "/")) != NULL) {
    > printf("token = "%s\"\n", token);
    > while ((token = strtok(NULL, "/")) != NULL) {
    > printf("token = \"%s\"\n", token);
    > }
    > }
    > }
    >
    > When I compile it using CC and got one Warning: String literal converted to
    > char* in assignment.
    > When I run it and got Segmentation Fault(coredump) .
    >
    > Then I changed defination as below:
    > char str[] = "5/90/45";
    > char *buf = str;
    >
    > Then this is no warning and I can get the correct result.
    >
    > Could you give me the reason?
    >
    > I think I can use char *point = "string" directly.
    >
    > Thansk.
    >
    > Franklin[/color]

    Comment

    • baumann@pan

      #3
      Re: question for char point.

      when i run your code in rh9, i got Segmentation Fault,
      but if your gdb prog, it runs ok, why?

      Comment

      • baumann@pan

        #4
        Re: question for char point.

        when i run your code in rh9, i got Segmentation Fault,
        but if run your code in debug mode ,
        gdb prog,
        and step by step it runs ok,

        ??????????????? ??????????????? ??????????????? ?????????????
        ??????????????? ???????why????? ??????????????? ?????????????
        ? ??????????????? ??????????????? ??????????????? ????????????

        Comment

        • S.Tobias

          #5
          Re: question for char point.

          Franklin Li <pengtaoli@hotm ai.com> wrote:[color=blue]
          > Hi all,[/color]
          [color=blue]
          > I have one simple program:
          > #define __EXTENSIONS__
          > #include <stdio.h>
          > #include <string.h>[/color]
          [color=blue]
          > int main() {
          > char *buf="5/90/45";[/color]
          Here `buf' points to a static string, which is in read-only
          memory. It's okay, until...[color=blue]
          > char *token;
          > char *lasts;[/color]
          [color=blue]
          > printf("tokeniz ing \"%s\" with strtok():\n", buf);
          > if ((token = strtok(buf, "/")) != NULL) {[/color]
          ....here: strtok tries to modify the string, which you are not
          allowed to do.
          You have to make a copy of the string, that can be modified, which....[color=blue]
          > printf("token = "%s\"\n", token);
          > while ((token = strtok(NULL, "/")) != NULL) {
          > printf("token = \"%s\"\n", token);
          > }
          > }
          > }[/color]
          [color=blue]
          > When I compile it using CC and got one Warning: String literal converted to
          > char* in assignment.
          > When I run it and got Segmentation Fault(coredump) .[/color]
          [color=blue]
          > Then I changed defination as below:
          > char str[] = "5/90/45";[/color]
          .... you're sort of doing here. `str' is an automatic array ("on stack"),
          which you initialize with the string literal (this initialization might
          for example copy the string from read-only memory to the new array).[color=blue]
          > char *buf = str;[/color]
          [color=blue]
          > Then this is no warning and I can get the correct result.[/color]
          [color=blue]
          > Could you give me the reason?[/color]
          [color=blue]
          > I think I can use char *point = "string" directly.[/color]

          You can use the pointer `point' anyway you want, but not what
          it points to.


          Another way to change the program would be to malloc() and copy,
          and pass the copy to strtok():
          char *buf="5/90/45";
          char *buf2=malloc(st rlen(buf)+1);
          /* ... (check) */
          strcpy(buf2, buf);
          if ((token = strtok(buf2, "/")) != NULL) {
          ^^^^

          --
          Stan Tobias
          mailx `echo siXtY@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`

          Comment

          • Keith Thompson

            #6
            Re: question for char point.

            "S.Tobias" <siXtY@FamOuS.B edBuG.pAlS.INVA LID> writes:[color=blue]
            > Franklin Li <pengtaoli@hotm ai.com> wrote:[/color]
            [...][color=blue][color=green]
            >> char *buf="5/90/45";[/color]
            > Here `buf' points to a static string, which is in read-only
            > memory. It's okay, until...[color=green]
            >> char *token;
            >> char *lasts;[/color]
            >[color=green]
            >> printf("tokeniz ing \"%s\" with strtok():\n", buf);
            >> if ((token = strtok(buf, "/")) != NULL) {[/color]
            > ...here: strtok tries to modify the string, which you are not
            > allowed to do.[/color]

            Actually, it's worse than that. The string literal may or may not be
            in read-only memory. Attempting it to modify it invokes undefined
            behavior.

            --
            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
            San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
            We must do something. This is something. Therefore, we must do this.

            Comment

            • Ari Lukumies

              #7
              Re: question for char point.

              Franklin Li wrote:[color=blue]
              > char *buf="5/90/45";[/color]

              You are allocating a pointer to a string literal (which may
              or may not reside in read-only memory; nevertheless, it's
              considered read-only).
              [color=blue]
              > if ((token = strtok(buf, "/")) != NULL) {[/color]

              strtok modifies the contents pointed to by buf, but the contents
              are read-only, so modification is not permitted.
              [color=blue]
              > Then I changed defination as below:
              > char str[] = "5/90/45";[/color]

              Here, you are allocating an array of chars containing the string "5/90/45".
              [color=blue]
              > char *buf = str;[/color]

              And here, you are allocating a pointer that points to that array,
              so the contents of the array (str) pointed to by the pointer (buf)
              are writable, thus no errors.

              You could use 'if ((token = strtok(str, "/")) != NULL)' as well or,
              as I'd prefer, 'if (!(token = strtok(str, "/")))'.

              -atl-
              --
              A multiverse is figments of its own creations

              Comment

              • john_bode@my-deja.com

                #8
                Re: question for char point.



                Franklin Li wrote:[color=blue]
                > Hi all,
                >
                > I have one simple program:
                > #define __EXTENSIONS__
                > #include <stdio.h>
                > #include <string.h>
                >
                > int main() {
                > char *buf="5/90/45";[/color]

                This declares buf to be a pointer to a string constant. String
                constants may or may not be writable, depending on the particular
                implementation; in your case, they're not. In general, it's best to
                assume they're not.

                strtok() has to be able to modify the buffer it's searching (it needs
                to be able to replace the delimiters with a 0). Hence your warning and
                your core dump (trying to write to non-writable memory).

                [snip]
                [color=blue]
                > Then I changed defination as below:
                > char str[] = "5/90/45";
                > char *buf = str;[/color]

                str is a statically allocated array of char, implicitly sized based on
                the initializer, and the contents of the initializer are copied to it.
                The contents of str are writable.
                [color=blue]
                >
                > Then this is no warning and I can get the correct result.
                >
                > Could you give me the reason?
                >
                > I think I can use char *point = "string" directly.
                >[/color]

                You can when you aren't trying to modify the string.

                Comment

                • Barry Schwarz

                  #9
                  Re: question for char point.

                  On 4 Jun 2005 14:57:30 -0700, john_bode@my-deja.com wrote:
                  [color=blue]
                  >
                  >
                  >Franklin Li wrote:[color=green]
                  >> Hi all,
                  >>
                  >> I have one simple program:
                  >> #define __EXTENSIONS__
                  >> #include <stdio.h>
                  >> #include <string.h>
                  >>
                  >> int main() {
                  >> char *buf="5/90/45";[/color]
                  >
                  >This declares buf to be a pointer to a string constant. String
                  >constants may or may not be writable, depending on the particular
                  >implementation ; in your case, they're not. In general, it's best to
                  >assume they're not.[/color]

                  Whether they are physically writable or not may be an implementation
                  detail but any attempt to modify a string literal invokes undefined
                  behavior.



                  <<Remove the del for email>>

                  Comment

                  Working...