Using &array with scanf

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chris Torek

    #16
    Re: Using &array with scanf

    In article <1136468408.906 944.212590@g49g 2000cwa.googleg roups.com>
    James Daughtry <mordock32@hotm ail.com> wrote:[color=blue]
    >Ah, now that's my problem. I made a beeline to that very paragraph to
    >prove my point, and the result was a quickie program much like the
    >following. He was trying to tell me through the output of the program
    >that array and &array result in the same address, and the type doesn't
    >matter because scanf will treat the same address like a pointer to
    >char, and the type mismatch is irrelevant.[/color]

    The problem with this argument lies in the phrase "the type mismatch
    is irrelevant". That may be the case on *his* machine, but it is
    definitely not the case on *every* machine.

    There are machines (Burroughs A-series) in which integers are stored
    in the same format as floating-point. (The compiler just makes sure
    that the fractional part is always zero.) On such a machine, if you
    do this:

    double x;

    ret = scanf("%d", (int *)&x);
    if (ret == 1)
    printf("I got %f\n", x);

    the code actually works! But it fails on most machines, because the
    type is *not* irrelevant on most machines.

    For a machine on which the type matters, find a 1960s era PR1ME, or
    perhaps even a 1980s Data General MV/10000 (aka Eclipse). (I am not
    sure whether the type "pointer to array N of char" on the Eclipse
    uses a word pointer, but if it does, the &array-with-scanf call will
    in fact fail.)
    [color=blue]
    >Unfortunatel y, he's the kind of person who uses the "it works for me"
    >argument. I know he's wrong, you know he's wrong, but he refuses to
    >admit that he's wrong until I can write a program that proves him
    >wrong. :-P[/color]

    If he is familiar with basketball, try the argument Steve Summit once
    repeated here (I am not sure where he got it):

    Someone told me that, in basketball, you have to bounce the
    ball off the floor; you can't hold the ball and run around the
    court. But I tried it and it works just fine. Obviously he
    does not understand basketball!

    Or, for Boston drivers, remember the rule about driving the wrong
    way on a one-way street ("it's OK as long as you're in reverse!").
    --
    In-Real-Life: Chris Torek, Wind River Systems
    Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
    email: forget about it http://web.torek.net/torek/index.html
    Reading email is like searching for food in the garbage, thanks to spammers.

    Comment

    • eerok

      #17
      Re: Using &amp;array with scanf

      Richard Heathfield wrote:[color=blue]
      > kaikai said:[/color]
      [color=blue][color=green]
      >> Since
      >> array and &array do have the same value,[/color][/color]
      [color=blue]
      > But they don't. The values have different types, so how can they be the
      > same?
      >
      > Are $3.14 and 3.14kg the same? Of course not.
      > Are 3.14% and 3.14km the same? Of course not.
      >
      > The type /matters/.[/color]
      [color=blue][color=green]
      >> It is okay to write such code,[/color][/color]
      [color=blue]
      > No, it isn't.[/color]

      Just to illustrate that it's *not* okay to get sloppy with
      types, here's an example that I discovered the other day.


      #include <stdio.h>

      char *t1 = "This can produce a segfault";
      char t2[] = "Best to do it this way ....";

      int
      main (void)
      {
      int ia = 3, ib = 2;

      /* no apparent problem (on my compiler) when I
      * index into either string */
      printf ("\nt1: '%s', 4th char: '%c'", t1, t1[ia]);
      printf ("\nt2: '%s', 4th char: '%c'\n", t2, t2[ia]);

      /* this is of course fine since we've declared
      * the string is an array of char */
      t2[ib] = t2[ia];
      printf ("\nNo segfault here.\n");

      /* this will produce a segfault with my compiler */
      t1[ib] = t1[ia];
      printf ("\nMaybe you'll get this far, but I don't.\n");

      return 0;
      }


      One might think that "a string is a string is a string" --
      that a pointer to a string is the same as the address of the
      first char of an array of chars. It usually seems to work
      this way, but the example above shows this isn't true.

      --
      "The secret of being boring is to say everything." - Voltaire


      Comment

      • Mark McIntyre

        #18
        Re: Using &amp;array with scanf

        On 5 Jan 2006 05:40:08 -0800, in comp.lang.c , "James Daughtry"
        <mordock32@hotm ail.com> wrote:
        [color=blue]
        >Unfortunatel y, he's the kind of person who uses the "it works for me"
        >argument.[/color]

        There's little point debating with such people. Give them the
        information, explain exactly once why its incorrect to do it
        otherwise, and walk away. If still they clean their gun while loaded,
        eventually Darwin will come to your rescue.
        Mark McIntyre
        --

        ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
        http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
        ----= East and West-Coast Server Farms - Total Privacy via Encryption =----

        Comment

        • Mark McIntyre

          #19
          Re: Using &amp;array with scanf

          On 5 Jan 2006 09:36:23 -0800, in comp.lang.c , "James Daughtry"
          <mordock32@hotm ail.com> wrote:
          [color=blue]
          >I'm sure that one day he'll get burned by UB and start to understand.
          >But until then, I have to work with the guy and suffer his "it works
          >for me" attitude.[/color]

          You could complain to your manager that his code is badly written and
          potentially dangerous, pointing to the sections of the Standard which
          are relevant. Even complete idiot managers tend to rely on
          documentation and will accept that over "it works for me".....

          Mark McIntyre
          --

          ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
          http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
          ----= East and West-Coast Server Farms - Total Privacy via Encryption =----

          Comment

          • Richard Heathfield

            #20
            Re: Using &amp;array with scanf

            eerok said:
            [color=blue]
            > Just to illustrate that it's *not* okay to get sloppy with
            > types, here's an example that I discovered the other day.[/color]

            The example you give doesn't fail because of a type issue, but because you
            attempt to write to storage that you're not supposed to write to. Had t1
            been pointing at writeable storage, you'd have had no segfault. For
            example, if you'd done this:
            [color=blue]
            > #include <stdio.h>
            >
            > char *t1 = "This can produce a segfault";
            > char t2[] = "Best to do it this way ....";[/color]

            char s[] = "This won't produce a segfault";
            t1 = s;

            you'd have had no problem, even though the type of t1 hasn't changed.



            --
            Richard Heathfield
            "Usenet is a strange place" - dmr 29/7/1999

            email: rjh at above domain (but drop the www, obviously)

            Comment

            • Keith Thompson

              #21
              Re: Using &amp;array with scanf

              Mark McIntyre <markmcintyre@s pamcop.net> writes:[color=blue]
              > On 5 Jan 2006 05:40:08 -0800, in comp.lang.c , "James Daughtry"
              > <mordock32@hotm ail.com> wrote:[color=green]
              >>Unfortunately , he's the kind of person who uses the "it works for me"
              >>argument.[/color]
              >
              > There's little point debating with such people. Give them the
              > information, explain exactly once why its incorrect to do it
              > otherwise, and walk away. If still they clean their gun while loaded,
              > eventually Darwin will come to your rescue.[/color]

              Natural selection is very much like undefined behavior; there's no
              reason to assume it will work to your benefit. The gun he's cleaning
              is just as likely to be pointed at your head. More relevantly, you're
              like to have to use the code he writes.

              Elsethread, I suggested several possibilities for demonstrating that
              the "it works for me" approach doesn't work. If *those* don't work,
              he may be impervious to reason. Deciding when to give up and accept
              this, either by walking away or by somehow preventing his bad code
              from affecting anything, is left as an exercise.

              But people can sometimes surprise you by turning around becoming
              reasonable when you least expect it (see "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

              • Dik T. Winter

                #22
                Re: Using &amp;array with scanf

                In article <1136468408.906 944.212590@g49g 2000cwa.googleg roups.com> "James Daughtry" <mordock32@hotm ail.com> writes:
                ....[color=blue]
                > Ah, now that's my problem. I made a beeline to that very paragraph to
                > prove my point, and the result was a quickie program much like the
                > following. He was trying to tell me through the output of the program
                > that array and &array result in the same address, and the type doesn't
                > matter because scanf will treat the same address like a pointer to
                > char, and the type mismatch is irrelevant.[/color]

                Note the difference:
                [color=blue][color=green][color=darkred]
                > > > char array[20];
                > > > scanf("%19s", &array);[/color][/color][/color]
                ....[color=blue]
                > printf("%p\n%p\ n", (void*)&array, (void*)array);[/color]

                Here &array and array are cast to (void *). So although originally
                &array and array may have had different representations , after the
                cast they are the some. So this proves exactly nothing. The original
                would have been correct if you had written:
                scanf("%19s", (char *)&array);
                I do not know whether there are, or have been, machines that use different
                representations for char pointers and pointers to an array of chars, but
                it is conceivable.
                --
                dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                Comment

                • Dik T. Winter

                  #23
                  Re: Using &amp;array with scanf

                  In article <lnbqyq77k2.fsf @nuthaus.mib.or g> Keith Thompson <kst-u@mib.org> writes:
                  ....[color=blue]
                  > On a machine where hardware addresses point to words, it's plausible
                  > that a byte pointer (char*) will have a different representation than
                  > a word pointer (such as int*); a word pointer could be a machine
                  > address, while a byte pointer could be a machine address plus an
                  > offset specifying one byte within the word. (The C compilers on Cray
                  > vector machines almost do this, but they put the offset into the
                  > otherwise unused high-order bits of the word pointer.)[/color]

                  The C compiler for the Data General did precisely what you wrote. That
                  is, a byte pointer would have the byte address in all 32 bits, a word
                  pointer would have a word address in the lowest 31 bits. And in a byte
                  pointer the lowest bit indicates the byte in a word.

                  And on both implementations when c is a char pointer, (char *)(int *)c
                  may lose information. (Ever tried to implement the original source of
                  the Bourne shell on such a machine?)

                  On the other hand, on both implementations a pointer to an array of
                  chars can not be a word pointer. (There are no padding bytes
                  between elements of an array.) So on those implementations the
                  representation of char * and char *[20] is the same. Consider
                  char a[5][5],
                  &(a[1]) must be a pointer to the array starting at the fifth byte, and so
                  can not be a word pointer. And it is the fifth byte because there is no
                  padding.

                  But this does *not* say that the pointers can not have different
                  representations , although I do not know of a system where that is
                  indeed the case.
                  --
                  dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                  home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                  Comment

                  • Dik T. Winter

                    #24
                    Re: Using &amp;array with scanf

                    In article <dpk1km01k0p@ne ws2.newsguy.com > Chris Torek <nospam@torek.n et> writes:
                    ....[color=blue]
                    > For a machine on which the type matters, find a 1960s era PR1ME, or
                    > perhaps even a 1980s Data General MV/10000 (aka Eclipse). (I am not
                    > sure whether the type "pointer to array N of char" on the Eclipse
                    > uses a word pointer, but if it does, the &array-with-scanf call will
                    > in fact fail.)[/color]

                    See my other article. It can not use a word pointer for a pointer to
                    array N of char, because there is no padding between elements of
                    arrays.
                    --
                    dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                    home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                    Comment

                    • Keith Thompson

                      #25
                      Re: Using &amp;array with scanf

                      "Dik T. Winter" <Dik.Winter@cwi .nl> writes:
                      [snip][color=blue]
                      > The C compiler for the Data General did precisely what you wrote. That
                      > is, a byte pointer would have the byte address in all 32 bits, a word
                      > pointer would have a word address in the lowest 31 bits. And in a byte
                      > pointer the lowest bit indicates the byte in a word.
                      >
                      > And on both implementations when c is a char pointer, (char *)(int *)c
                      > may lose information. (Ever tried to implement the original source of
                      > the Bourne shell on such a machine?)
                      >
                      > On the other hand, on both implementations a pointer to an array of
                      > chars can not be a word pointer. (There are no padding bytes
                      > between elements of an array.) So on those implementations the
                      > representation of char * and char *[20] is the same. Consider
                      > char a[5][5],
                      > &(a[1]) must be a pointer to the array starting at the fifth byte, and so
                      > can not be a word pointer. And it is the fifth byte because there is no
                      > padding.[/color]

                      You don't even have to resort to 2-dimensional arrays. Consider

                      char a[6];
                      typedef char (*array_ptr)[5];
                      array_ptr p0 = (array_ptr)a;
                      array_ptr p1 = (array_ptr)(a+1 );

                      Both p0 and p1 are (I think!) valid pointers to arrays of 5 chars. p0
                      points to the array starting at element 0 of a; p1 points to the array
                      starting at element 1 of a (i.e., the last 5 of the 6 elements of a).
                      [color=blue]
                      > But this does *not* say that the pointers can not have different
                      > representations , although I do not know of a system where that is
                      > indeed the case.[/color]

                      Agreed. Even if they happen to have the same representation on all
                      possible platforms, I wouldn't find it particularly convenient to be
                      able to make that assumption.

                      Note that the code snippet above doesn't assume anything about the
                      representations of the various types of pointers. It uses casts
                      (explicit conversions), so the compiler will take care of any change
                      of representation necessary to convert from one pointer type to
                      another. The original question was about arguments to scanf, for
                      which no such conversion takes place.

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

                      • Jordan Abel

                        #26
                        Re: Using &amp;array with scanf

                        On 2006-01-06, Dik T. Winter <Dik.Winter@cwi .nl> wrote:[color=blue]
                        > In article <dpk1km01k0p@ne ws2.newsguy.com > Chris Torek <nospam@torek.n et> writes:
                        > ...[color=green]
                        > > For a machine on which the type matters, find a 1960s era PR1ME, or
                        > > perhaps even a 1980s Data General MV/10000 (aka Eclipse). (I am not
                        > > sure whether the type "pointer to array N of char" on the Eclipse
                        > > uses a word pointer, but if it does, the &array-with-scanf call will
                        > > in fact fail.)[/color]
                        >
                        > See my other article. It can not use a word pointer for a pointer to
                        > array N of char, because there is no padding between elements of
                        > arrays.[/color]

                        What about padding at the end of an array? Is a pointer to char
                        guaranteed to be convertible to a pointer to an array of chars?

                        Comment

                        • eerok

                          #27
                          Re: Using &amp;array with scanf

                          Richard Heathfield wrote:[color=blue]
                          > eerok said:[/color]
                          [color=blue][color=green]
                          >> Just to illustrate that it's *not* okay to get sloppy with
                          >> types, here's an example that I discovered the other day.[/color][/color]
                          [color=blue]
                          > The example you give doesn't fail because of a type issue, but because you
                          > attempt to write to storage that you're not supposed to write to. Had t1
                          > been pointing at writeable storage, you'd have had no segfault. For
                          > example, if you'd done this:
                          >[color=green]
                          >> #include <stdio.h>
                          >>
                          >> char *t1 = "This can produce a segfault";
                          >> char t2[] = "Best to do it this way ....";[/color]
                          >
                          > char s[] = "This won't produce a segfault";
                          > t1 = s;
                          >
                          > you'd have had no problem, even though the type of t1 hasn't changed.[/color]

                          Thanks for your response, which forced me to do some reading.
                          If my understanding is correct now, my problem was caused by
                          trying to write to a string literal, resulting in UB.

                          I'm trying to scrape the rust off my C skills, which were
                          learned long ago on a PDP-11 ... between the things I've
                          forgotten and the things that have changed, I'm pretty much a
                          newbie again :-)

                          --
                          "The secret of being boring is to say everything." - Voltaire



                          Comment

                          • Richard Heathfield

                            #28
                            Re: Using &amp;array with scanf

                            eerok said:
                            [color=blue]
                            > Thanks for your response, which forced me to do some reading.
                            > If my understanding is correct now, my problem was caused by
                            > trying to write to a string literal, resulting in UB.[/color]

                            Correct.
                            [color=blue]
                            > I'm trying to scrape the rust off my C skills, which were
                            > learned long ago on a PDP-11 ... between the things I've
                            > forgotten and the things that have changed, I'm pretty much a
                            > newbie again :-)[/color]

                            You appear to learn reasonably quickly. Stick around clc, read more (much
                            more) than you write, and ask when you have to. If you do that, then within
                            a few months you should be sufficiently back up to speed to consider
                            answering questions here (which, if it can be done regularly without
                            getting your rear end handed to you on a platter, is almost enough to
                            qualify you as an "expert").

                            --
                            Richard Heathfield
                            "Usenet is a strange place" - dmr 29/7/1999

                            email: rjh at above domain (but drop the www, obviously)

                            Comment

                            • Dik T. Winter

                              #29
                              Re: Using &amp;array with scanf

                              In article <slrndrrpa0.dv9 .random832@rand om.yi.org> Jordan Abel <random832@gmai l.com> writes:[color=blue]
                              > On 2006-01-06, Dik T. Winter <Dik.Winter@cwi .nl> wrote:[/color]
                              ....[color=blue][color=green]
                              > > See my other article. It can not use a word pointer for a pointer to
                              > > array N of char, because there is no padding between elements of
                              > > arrays.[/color]
                              >
                              > What about padding at the end of an array?[/color]

                              No. The size of an array is the product of the number of elements and
                              the size of an element.
                              [color=blue]
                              > Is a pointer to char
                              > guaranteed to be convertible to a pointer to an array of chars?[/color]

                              I do not think it is guaranteed that way. It *is* guaranteed the
                              other way.
                              --
                              dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                              home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                              Comment

                              • eerok

                                #30
                                Re: Using &amp;array with scanf

                                Richard Heathfield wrote:[color=blue]
                                > eerok said:[/color]

                                [...]
                                [color=blue][color=green]
                                >> I'm trying to scrape the rust off my C skills, which were
                                >> learned long ago on a PDP-11 ... between the things I've
                                >> forgotten and the things that have changed, I'm pretty much a
                                >> newbie again :-)[/color][/color]
                                [color=blue]
                                > You appear to learn reasonably quickly. Stick around clc, read more (much
                                > more) than you write, and ask when you have to. If you do that, then within
                                > a few months you should be sufficiently back up to speed to consider
                                > answering questions here (which, if it can be done regularly without
                                > getting your rear end handed to you on a platter, is almost enough to
                                > qualify you as an "expert").[/color]

                                Thanks, Richard. This newsgroup has been an enormous help to
                                me in the short time that I've been visiting here. Keep up
                                the good work :-)

                                --
                                "The secret of being boring is to say everything." - Voltaire



                                Comment

                                Working...