Return of a string that fails

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • nembo kid

    Return of a string that fails

    My homework is to make a simple function that, given a unsigned char,
    should returns its bit string representation.

    I tried to drop down some code (as follows) but it doesn't work.
    Compiling is successfully, but print8bit() doesn't return anything.

    Was wondering where I'm mistaking. Thanks in advance for your help.

    /* code starts here */

    char* print8bit (unsigned char n)
    {
    char s[9]; /* Allocate an array of 8+1 char */

    int i, j; /* Counter variables */

    for (j=7,i=0; j>=0,i<=7 ; j--,i++)
    {
    if(n & (1<<i))
    s[j]='1';
    else
    s[j]='0';
    }

    s[8]='\0'; /* Marker of end of string */

    return s; /* Return the first address of char array? */
    }

    int main(void)
    {

    char* str = print8bit(128); /* str[] now should be '1000000' */

    printf("%d: %s", 128, str); /* on stdout is printed only '128:' */

    return 0;
    }

    /* code ends here */


  • vippstar@gmail.com

    #2
    Re: Return of a string that fails

    On May 20, 1:52 pm, nembo kid <nembo@kidwrote :
    My homework is to make a simple function that, given a unsigned char,
    should returns its bit string representation.
    HW questions, hmmmmm...
    I tried to drop down some code (as follows) but it doesn't work.
    Compiling is successfully, but print8bit() doesn't return anything.
    >
    Was wondering where I'm mistaking. Thanks in advance for your help.
    You return a pointer to an object whose lifetime is over. That's
    undefined behavior.
    <snip code>

    Comment

    • nembo kid

      #3
      Re: Return of a string that fails

      vippstar@gmail. com ha scritto:
      You return a pointer to an object whose lifetime is over. That's
      undefined behavior.
      Ok, found..,.that silly I am.

      Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
      heap I shouldn't have any issue....seems that the same happens with
      linked list (that are allocated on the heap).

      So either I'd use the qualificator 'static' to "keep on alive" s after
      exiting from the function or pass its address as parameter (a pointer to
      a pointer).

      Both solutions are equivalent?

      Thanks again.

      Comment

      • vippstar@gmail.com

        #4
        Re: Return of a string that fails

        On May 20, 2:12 pm, nembo kid <nembo@kidwrote :
        vipps...@gmail. com ha scritto:
        >
        You return a pointer to an object whose lifetime is over. That's
        undefined behavior.
        >
        Ok, found..,.that silly I am.
        >
        Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
        heap I shouldn't have any issue....seems that the same happens with
        linked list (that are allocated on the heap).
        >
        So either I'd use the qualificator 'static' to "keep on alive" s after
        exiting from the function or pass its address as parameter (a pointer to
        a pointer).
        >
        Both solutions are equivalent?
        No, the second solution, assuming void f(unsigned char c, char **s)
        will not work unless you assign *s a static array or a value from
        malloc/calloc/realloc.
        Here's the best solution:

        void f(unsigned char c, char *s)

        And write to s. You may assume that 's' is at least CHAR_BIT+1 long,
        and the user of the function is responsible to make sure it is.

        Comment

        • Bart

          #5
          Re: Return of a string that fails

          On May 20, 12:12 pm, nembo kid <nembo@kidwrote :
          vipps...@gmail. com ha scritto:
          >
          You return a pointer to an object whose lifetime is over. That's
          undefined behavior.
          >
          Ok, found..,.that silly I am.
          >
          Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
          heap I shouldn't have any issue....seems that the same happens with
          linked list (that are allocated on the heap).
          >
          So either I'd use the qualificator 'static' to "keep on alive" s after
          exiting from the function or pass its address as parameter (a pointer to
          a pointer).
          >
          Both solutions are equivalent?
          Using 'static' is an instant fix.

          But has the disadvantage that, if the caller doesn't use or copy the
          value in s straightaway, the function can be called elsewhere and s
          can be overwritten.


          -- Bartc

          Comment

          • Joachim Schmitz

            #6
            Re: Return of a string that fails


            "nembo kid" <nembo@kidschri eb im Newsbeitrag
            news:4832ac7d$0 $35955$4fafbaef @reader2.news.t in.it...
            My homework is to make a simple function that, given a unsigned char,
            should returns its bit string representation.
            >
            I tried to drop down some code (as follows) but it doesn't work. Compiling
            is successfully, but print8bit() doesn't return anything.
            >
            Was wondering where I'm mistaking. Thanks in advance for your help.
            >
            /* code starts here */
            #include <limits.h/* for CHAR_BIT, portable */
            #include <stdio.h/* for printf(), undefined behavoir otherwise */
            >
            char* print8bit (unsigned char n)
            {
            char s[9]; /* Allocate an array of 8+1 char */
            static char s[CHAR_BIT+1]; /* Allocate an array of CHAR_BITS+1 char */
            >
            int i, j; /* Counter variables */
            >
            for (j=7,i=0; j>=0,i<=7 ; j--,i++)
            for (j=CHAR_BIT,i=0 ; j>0,i<CHAR_BIT ; j--,i++)
            {
            if(n & (1<<i))
            s[j]='1';
            else
            s[j]='0';
            }
            >
            s[8]='\0'; /* Marker of end of string */
            s[CHAR_BIT]='\0'; /* Marker of end of string */
            >
            return s; /* Return the first address of char array? */
            }
            >
            int main(void)
            {
            >
            char* str = print8bit(128); /* str[] now should be '1000000' */
            >
            printf("%d: %s", 128, str); /* on stdout is printed only '128:' */
            >
            return 0;
            }
            >
            /* code ends here */
            Bye, Jojo


            Comment

            • Richard Bos

              #7
              Re: Return of a string that fails

              nembo kid <nembo@kidwrote :
              vippstar@gmail. com ha scritto:
              >
              You return a pointer to an object whose lifetime is over. That's
              undefined behavior.
              >
              Ok, found..,.that silly I am.
              >
              Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
              heap I shouldn't have any issue....seems that the same happens with
              linked list (that are allocated on the heap).
              "Stack" and "heap" are deceptive terms. What matters is the duration of
              the object you return, not where it is placed. You might want to read
              questions 7.5a and 7.5b from the FAQ:
              <http://c-faq.com/malloc/retaggr.htmland
              <http://c-faq.com/malloc/retaggr2.html>.

              Richard

              Comment

              • Thad Smith

                #8
                Re: Return of a string that fails

                Joachim Schmitz wrote:
                "nembo kid" <nembo@kidschri eb im Newsbeitrag
                news:4832ac7d$0 $35955$4fafbaef @reader2.news.t in.it...
                >My homework is to make a simple function that, given a unsigned char,
                >should returns its bit string representation.
                > int i, j; /* Counter variables */
                >>
                > for (j=7,i=0; j>=0,i<=7 ; j--,i++)
                for (j=CHAR_BIT,i=0 ; j>0,i<CHAR_BIT ; j--,i++)
                or simply

                for (j=CHAR_BIT,i=0 ; i<CHAR_BIT ; j--,i++)

                The expression j>=0 is evaluated and discarded. Most compilers will issue
                a warning for this.

                --
                Thad

                Comment

                • Joachim Schmitz

                  #9
                  Re: Return of a string that fails

                  Thad Smith wrote:
                  Joachim Schmitz wrote:
                  >"nembo kid" <nembo@kidschri eb im Newsbeitrag
                  >news:4832ac7d$ 0$35955$4fafbae f@reader2.news. tin.it...
                  >>My homework is to make a simple function that, given a unsigned
                  >>char, should returns its bit string representation.
                  >
                  >> int i, j; /* Counter variables */
                  >>>
                  >> for (j=7,i=0; j>=0,i<=7 ; j--,i++)
                  >for (j=CHAR_BIT,i=0 ; j>0,i<CHAR_BIT ; j--,i++)
                  >
                  or simply
                  >
                  for (j=CHAR_BIT,i=0 ; i<CHAR_BIT ; j--,i++)
                  >
                  The expression j>=0 is evaluated and discarded. Most compilers will
                  issue a warning for this.
                  True, copy'n'paste error on my side...

                  Bye, Jojo


                  Comment

                  • Kenneth Brody

                    #10
                    Re: Return of a string that fails

                    vippstar@gmail. com wrote:
                    >
                    On May 20, 1:52 pm, nembo kid <nembo@kidwrote :
                    My homework is to make a simple function that, given a unsigned char,
                    should returns its bit string representation.
                    HW questions, hmmmmm...
                    Well, (1) he says it's homework, right up front, and (2) he posts
                    his current code and asks for help on finding his error. Sounds like
                    someone who deserves help, which I see you have provided. I don't
                    think anyone here has a problem helping people with their homework.
                    It's the ones who come here asking us to _do_ their homework that
                    are the problem.

                    Finally, those who post with gender-neutral names will be refered to
                    as "he" until contradictory information is provided. :-)

                    [...]

                    --
                    +-------------------------+--------------------+-----------------------+
                    | Kenneth J. Brody | www.hvcomputer.com | #include |
                    | kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
                    +-------------------------+--------------------+-----------------------+
                    Don't e-mail me at: <mailto:ThisIsA SpamTrap@gmail. com>

                    Comment

                    • Pietro Cerutti

                      #11
                      Re: Return of a string that fails

                      nembo kid wrote:
                      vippstar@gmail. com ha scritto:
                      >
                      >You return a pointer to an object whose lifetime is over. That's
                      >undefined behavior.
                      >
                      Ok, found..,.that silly I am.
                      >
                      Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
                      heap I shouldn't have any issue....seems that the same happens with
                      linked list (that are allocated on the heap).
                      >
                      So either I'd use the qualificator 'static' to "keep on alive" s after
                      exiting from the function or pass its address as parameter (a pointer to
                      a pointer).
                      >
                      Both solutions are equivalent?
                      The first solution isn't reentrant, which means that if your program is
                      multi-threaded, two threads calling your function roughly at the same
                      time could contemporaneous ly write on the static buffer. What you would
                      get is garbage.

                      I would suggest to pass the address of a pre-allocated char array, or to
                      pass a pointer to a pointer to char and let your function dynamically
                      allocate it. The caller would then need to free it.

                      char *print8bit(unsi gned char n, char **result)
                      {
                      if(!(*result = malloc(CHAR_BIT + 1)))
                      return (NULL);
                      /*
                      * put your things into *result[x]
                      */
                      }
                      >
                      Thanks again.

                      --
                      Pietro Cerutti

                      Comment

                      • nembo kid

                        #12
                        Re: Return of a string that fails

                        Kenneth Brody ha scritto:
                        It's the ones who come here asking us to _do_ their homework that
                        are the problem.
                        Finally, those who post with gender-neutral names will be refered to
                        as "he" until contradictory information is provided. :-)

                        Sorry, but You are wrong.

                        Comment

                        Working...