Puzzling program

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rajeet Dalawal

    Puzzling program

    Good day group.

    I was asked in an interview to explain the behavior of this program.

    void main()
    {
    char *s = "abc";
    int *i = (int *) s;
    printf("%x", *i);
    }

    The question is: why is the output 636261? I don't think I know enough
    about C to understand how the conversions between pointer types are
    occurring.

    Thanks for any help.

    RD

  • Malcolm McLean

    #2
    Re: Puzzling program


    "Rajeet Dalawal" <rd@mailinator. comwrote in message
    news:slrnfbkh1h .2k8.spamoff@no spam.invalid...
    Good day group.
    >
    I was asked in an interview to explain the behavior of this program.
    >
    void main()
    {
    char *s = "abc";
    int *i = (int *) s;
    printf("%x", *i);
    }
    >
    The question is: why is the output 636261? I don't think I know enough
    about C to understand how the conversions between pointer types are
    occurring.
    >
    Thanks for any help.
    >
    The interviewer is looking for you to understand that C data is stored in
    memory as bytes, and that by playing about with pointers you can cause the
    bits to be reinterpreted as different types.

    --
    Free games and programming goodies.



    Comment

    • Joe Wright

      #3
      Re: Puzzling program

      Rajeet Dalawal wrote:
      Good day group.
      >
      I was asked in an interview to explain the behavior of this program.
      >
      void main()
      {
      char *s = "abc";
      int *i = (int *) s;
      printf("%x", *i);
      }
      >
      The question is: why is the output 636261? I don't think I know enough
      about C to understand how the conversions between pointer types are
      occurring.
      >
      Thanks for any help.
      >
      RD
      >
      Please allow me..

      #include <stdio.h>
      int main(void) {
      char *s = "abc";
      int *i = (int *)s;
      printf("%08x", *i);
      return 0;
      }

      I'll assume Intel CPU and ASCII characters.
      You have s pointing to a four-byte string, in hex, 61 62 63 00.
      Intel is little-endian. When you treat those four bytes as an int and
      the print it as hex, the result is 00636261.

      --
      Joe Wright
      "Everything should be made as simple as possible, but not simpler."
      --- Albert Einstein ---

      Comment

      • Malcolm McLean

        #4
        Re: Puzzling program


        "Keith Thompson" <kst-u@mib.orgwrote in message
        news:lnejid1uqb .fsf@nuthaus.mi b.org...
        It's either a very bad interview question or a very good one. 5
        points for explaining the behavior; 50 points for finding all the
        errors in the code (and -100 points to the interviewer if he thinks
        it's a valid program).
        >
        You could point out all the errors and nonportable assumptions in the code.
        But you are not interviewing the interviewer, probably. He's deciding
        whether he wants you, and you would be very uncertain of the reaction you
        would get.
        Companies want "team players", corporate-speak for the word they dare not
        use, obedience.

        --
        Free games and programming goodies.


        Comment

        • Richard Heathfield

          #5
          Re: Puzzling program

          Rajeet Dalawal said:
          Good day group.
          >
          I was asked in an interview to explain the behavior of this program.
          >
          void main()
          {
          char *s = "abc";
          int *i = (int *) s;
          printf("%x", *i);
          }
          >
          The question is: why is the output 636261?
          No, it isn't. The question is: why is the interviewer asking you this
          question? Is it to test your understanding that the program is
          bug-ridden? The program comprises five lines of code, if we don't count
          the braces. I can immediately see three instances of undefined
          behaviour and three instances of poor style (not "pretty-pretty" style,
          but "let's-prevent-bugs-and-get-the-output-right" style. The bug rate
          (errors per line) is simply staggering - possibly even higher than
          Schildt's.

          Others have pointed out the errors themselves, so I won't repeat them
          here.

          In your situation, I would explain, not the *output* of the program, but
          the *problems* with it. If the interviewer starts nodding
          encouragingly, that might indicate that it's a "lamer test", in which
          case all might yet be well.

          If, on the other hand, he or she looks puzzled or disbelieving as you
          explain the problems, thank him or her for the sandwiches and coffee,
          make your excuses, and leave. You don't want to work there.

          --
          Richard Heathfield <http://www.cpax.org.uk >
          Email: -www. +rjh@
          Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
          "Usenet is a strange place" - dmr 29 July 1999

          Comment

          • Richard Tobin

            #6
            Re: Puzzling program

            In article <5hv2btF3iko0qU 1@mid.individua l.net>,
            Martin Ambuhl <mambuhl@earthl ink.netwrote:
            >Be glad you don't understand this piece of garbage. Anyone who could
            >write this crap and expect a known result of compilation, not to mention
            >execution, is a fool. You don't want to work with such people. They
            >will create bugs as fast as they code, and you will be assigned to fix them.
            I completely disagree. Obviously such code is not portable, and
            unlikely to be useful even if the system is known. But knowing the
            details of the C standard isn't all there is to being a C programmer,
            and someone who has no idea what is going on underneath would not be
            my choice. We should encourage the desire to know how things work.

            -- Richard
            --
            "Considerat ion shall be given to the need for as many as 32 characters
            in some alphabets" - X3.4, 1963.

            Comment

            • Keith Thompson

              #7
              Re: Puzzling program

              "Malcolm McLean" <regniztar@btin ternet.comwrite s:
              "Keith Thompson" <kst-u@mib.orgwrote in message
              news:lnejid1uqb .fsf@nuthaus.mi b.org...
              >It's either a very bad interview question or a very good one. 5
              >points for explaining the behavior; 50 points for finding all the
              >errors in the code (and -100 points to the interviewer if he thinks
              >it's a valid program).
              >>
              You could point out all the errors and nonportable assumptions in the
              code. But you are not interviewing the interviewer, probably. He's
              deciding whether he wants you, and you would be very uncertain of the
              reaction you would get.
              Companies want "team players", corporate-speak for the word they dare
              not use, obedience.
              This has veered off-topic, so I'll just strongly disagree and move on.
              If you'd care to redirect this to a more appropriate newsgroup (I'm
              not sure which one), I might follow the discussion there.

              --
              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."
              -- Antony Jay and Jonathan Lynn, "Yes Minister"

              Comment

              • Richard Tobin

                #8
                Re: Puzzling program

                In article <AtmdnZElSYDTxS fb4p2dnAA@bt.co m>,
                Richard Heathfield <rjh@see.sig.in validwrote:
                >The question is: why is the output 636261?
                >No, it isn't. The question is: why is the interviewer asking you this
                >question? Is it to test your understanding that the program is
                >bug-ridden? The program comprises five lines of code, if we don't count
                >the braces. I can immediately see three instances of undefined
                >behaviour and three instances of poor style (not "pretty-pretty" style,
                >but "let's-prevent-bugs-and-get-the-output-right" style. The bug rate
                >(errors per line) is simply staggering - possibly even higher than
                >Schildt's.
                >
                >Others have pointed out the errors themselves, so I won't repeat them
                >here.
                >
                >In your situation, I would explain, not the *output* of the program, but
                >the *problems* with it. If the interviewer starts nodding
                >encouragingl y, that might indicate that it's a "lamer test", in which
                >case all might yet be well.
                >
                >If, on the other hand, he or she looks puzzled or disbelieving as you
                >explain the problems, thank him or her for the sandwiches and coffee,
                >make your excuses, and leave. You don't want to work there.
                While all this is quite reasonable, it's still true that any
                experienced C programmer should be able to explain why the output is,
                in fact, quite likely to be 636261.

                -- Richard

                --
                "Considerat ion shall be given to the need for as many as 32 characters
                in some alphabets" - X3.4, 1963.

                Comment

                • Keith Thompson

                  #9
                  Re: Puzzling program

                  Martin Ambuhl <mambuhl@earthl ink.netwrites:
                  Rajeet Dalawal wrote:
                  >Good day group.
                  >I was asked in an interview to explain the behavior of this program.
                  >void main()
                  >{
                  > char *s = "abc";
                  > int *i = (int *) s;
                  > printf("%x", *i);
                  >}
                  >The question is: why is the output 636261?
                  >
                  Because:
                  a) The illiterate return type 'void' for main makes all bets off.
                  b) The illiterate omission of the required prototype for the variadic
                  function printf makes all bets off.
                  c) The illiterate absence of an end-of-line character ending the
                  last line of output makes all bets off.
                  Dang, I missed that one!

                  [other excellent points snipped]
                  Be glad you don't understand this piece of garbage. Anyone who could
                  write this crap and expect a known result of compilation, not to
                  mention execution, is a fool. You don't want to work with such
                  people. They will create bugs as fast as they code, and you will be
                  assigned to fix them.
                  Yes, it's undefined garbage, but I understand what it's *intended* to
                  do, and I'd actually expect it to yield one of a couple of results on
                  most systems, though I'd be unsurprised to see something radically
                  different . (Yeah, I went and tried it before writing that.)

                  If someone wrote that program *and thought it was valid*, I'd assume
                  the author was either (a) a newbie who needs to unlearn a few things
                  before he can move on to write decent code (ignorance is curable) or
                  (b) incompetent.

                  *But* any experienced C programmer should, in addition to recognizing
                  the astonishing number of bugs, be able to explain *why* the program
                  prints 636261 (and what that says about the implementation) . Even
                  competent programmers make mistakes (though not with the density seen
                  in this example), and understanding the probable explanation for the
                  specific behavior of a buggy program is a valuable skill. Certainly
                  the goal should be to eliminate any undefined behavior (and, if
                  possible unspecified behavior) and produce a correct program, but
                  understanding a particular manifestation of UB can be an important
                  step in achieving that goal.

                  And, as I speculated elsethread, the errors may actually have been the
                  point of the interview question.

                  --
                  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."
                  -- Antony Jay and Jonathan Lynn, "Yes Minister"

                  Comment

                  • Kelsey Bjarnason

                    #10
                    Re: Puzzling program

                    [snips]

                    On Thu, 09 Aug 2007 00:26:19 +0100, Malcolm McLean wrote:
                    You could point out all the errors and nonportable assumptions in the code.
                    But you are not interviewing the interviewer, probably. He's deciding
                    whether he wants you, and you would be very uncertain of the reaction you
                    would get.
                    Companies want "team players", corporate-speak for the word they dare not
                    use, obedience.
                    Perhaps they do, but I've seen questions such as this _precisely_ to
                    determine whether you're the sort who turns down the warning level and
                    prays, or if you're the sort who has at least some clue why the code is
                    wrong.

                    Comment

                    • Richard Heathfield

                      #11
                      Re: Puzzling program

                      Richard Tobin said:

                      <snip>
                      While all this is quite reasonable, it's still true that any
                      experienced C programmer should be able to explain why the output is,
                      in fact, quite likely to be 636261.
                      But it isn't! On my system, for example, the program prints "a suffusion
                      of yellow".

                      --
                      Richard Heathfield <http://www.cpax.org.uk >
                      Email: -www. +rjh@
                      Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
                      "Usenet is a strange place" - dmr 29 July 1999

                      Comment

                      • regis

                        #12
                        Re: Puzzling program

                        Keith Thompson wrote:
                        >> printf("%x", *i);
                        >
                        Also, calling printf with no prototype in scope invokes undefined
                        behavior (the fix is to add a '#include <stdio.h>' to the top of the
                        source file). And "%x" is the wrong format for printing an int;
                        probably 'i' should have been declared as an unsigned int* (the
                        standard *almost* says that it will work anyway, but it's not
                        something I'd be comfortable counting on).
                        also, no newline and the end of the program is reached...

                        Comment

                        • Charlton Wilbur

                          #13
                          Re: Puzzling program

                          >>>>"RH" == Richard Heathfield <rjh@see.sig.in validwrites:

                          RHRichard Tobin said: <snip>
                          >While all this is quite reasonable, it's still true that any
                          >experienced C programmer should be able to explain why the
                          >output is, in fact, quite likely to be 636261.
                          RHBut it isn't! On my system, for example, the program prints "a
                          RHsuffusion of yellow".

                          Fortunately, you have a DeathStation 2000. I ran it on my
                          DeathStation 3000, and I'm hoping my eyebrows grow back.

                          Charlton


                          --
                          Charlton Wilbur
                          cwilbur@chromat ico.net

                          Comment

                          • Charlton Wilbur

                            #14
                            Re: Puzzling program

                            >>>>"MMcL" == Malcolm McLean <regniztar@btin ternet.comwrite s:

                            MMcLYou could point out all the errors and nonportable
                            MMcLassumptions in the code. But you are not interviewing the
                            MMcLinterviewer , probably. He's deciding whether he wants you,
                            MMcLand you would be very uncertain of the reaction you would
                            MMcLget.

                            If the interviewer quizzes you on bad code and expects you to toe the
                            line rather than fix things, that's a strong clue about the corporate
                            culture that a competent and professional programmer ignores at his or
                            her peril. And while the interviewer is deciding whether or not he
                            wants to hire the candidate, the candidate is deciding whether or not
                            he wants to work for that company.

                            I've been on more than one interview where it was clear by the end of
                            the interview that this was *not* a company I had any interest in
                            working for, for issues of culture and group competence.

                            Charlton


                            --
                            Charlton Wilbur
                            cwilbur@chromat ico.net

                            Comment

                            • jaysome

                              #15
                              Re: Puzzling program

                              On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
                              <mambuhl@earthl ink.netwrote:
                              >Rajeet Dalawal wrote:
                              >Good day group.
                              >>
                              >I was asked in an interview to explain the behavior of this program.
                              >>
                              >void main()
                              >{
                              > char *s = "abc";
                              > int *i = (int *) s;
                              > printf("%x", *i);
                              >}
                              >>
                              >The question is: why is the output 636261?
                              >
                              >Because:
                              >a) The illiterate return type 'void' for main makes all bets off.
                              >b) The illiterate omission of the required prototype for the variadic
                              function printf makes all bets off.
                              >c) The illiterate absence of an end-of-line character ending the
                              last line of output makes all bets off.
                              What do you mean by "all bets off"? Do you mean undefined behavior? I
                              don't think it is undefined behavior.

                              Consider:

                              #include <stdio.h>
                              int main(void)
                              {
                              printf("Hello world!");
                              return 0;
                              }

                              There is no end-of-line character ending the last line of output. Yet,
                              as far as the C standard is concerned, this is well-defined behavior.
                              The definition of the word "flushed" is found in Section 7.19.3.(4):

                              "A file may be disassociated from a controlling stream by closing the
                              file. Output streams are flushed (any unwritten buffer contents are
                              transmitted to the host environment) before the stream is
                              disassociated from the file."

                              Then, from Section 7.19.3.(5):

                              "The file may be subsequently reopened, by the same or another program
                              execution, and its contents reclaimed or modified (if it can be
                              repositioned at its start). If the main function returns to its
                              original caller, or if the exit function is called, all open files are
                              closed (hence all output streams are flushed) before program
                              termination."

                              From these two sections, we know that, before program termination, the
                              following statement:

                              printf("Hello world!");

                              results in any unwritten buffer contents being transmitted to the host
                              environment.

                              What the host environment does with a final buffer that does not
                              contain an "end-of-line" character is completely beyond the
                              jurisdiction of the C standard, and thusly there is no possibility of
                              undefined behavior.

                              Admittedly, it is not a good idea to omit an end-of-line character
                              ending the last line of output. That's because what you expect to be
                              output may not be output, and it all depends on the host environment
                              as to whether or not the program output behaves as expected. Again,
                              this is not undefined behavior, as far as the C standard is concerned.

                              Regards
                              --
                              jay


                              Comment

                              Working...