malloc() for struct member

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

    malloc() for struct member

    Hello, I have a very simple question that I'm a bit confused about
    right now. Is it OK to allocate memory by malloc() or calloc() for a
    struct member and then call free() on it? For example, I have the code
    below.

    struct mystruct {
    int a;
    char *b;
    int c;
    };

    struct mystruct myobject;

    myobject.b = (char *)malloc(50);
    ....
    ....
    free(myobject.b );

    Is the above code OK, or is there any potential problem with it?

    Thanks!

  • Keith Thompson

    #2
    Re: malloc() for struct member

    "googler" <pinaki_m77@yah oo.com> writes:[color=blue]
    > Hello, I have a very simple question that I'm a bit confused about
    > right now. Is it OK to allocate memory by malloc() or calloc() for a
    > struct member and then call free() on it? For example, I have the code
    > below.
    >
    > struct mystruct {
    > int a;
    > char *b;
    > int c;
    > };
    >
    > struct mystruct myobject;
    >
    > myobject.b = (char *)malloc(50);
    > ...
    > ...
    > free(myobject.b );
    >
    > Is the above code OK, or is there any potential problem with it?[/color]

    The only problem I can see is that you cast the result of malloc().
    This is legal but unnecessary, and can mask errors. Change the line
    to

    myobject.b = malloc(50);

    Other than that, I don't see anything wrong.

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

    • Barry Schwarz

      #3
      Re: malloc() for struct member

      On 5 Oct 2005 20:06:15 -0700, "googler" <pinaki_m77@yah oo.com> wrote:
      [color=blue]
      >Hello, I have a very simple question that I'm a bit confused about
      >right now. Is it OK to allocate memory by malloc() or calloc() for a
      >struct member and then call free() on it? For example, I have the code
      >below.
      >
      >struct mystruct {
      > int a;
      > char *b;
      > int c;
      >};
      >
      >struct mystruct myobject;
      >
      >myobject.b = (char *)malloc(50);[/color]

      Don't cast the return from malloc. It doesn't help and may cause the
      compiler to suppress a diagnostic you really want to see.[color=blue]
      >...
      >...
      >free(myobject. b);[/color]

      This is how you would avoid a memory leak. What prompted the
      question?
      [color=blue]
      >
      >Is the above code OK, or is there any potential problem with it?
      >
      >Thanks![/color]


      <<Remove the del for email>>

      Comment

      • googler

        #4
        Re: malloc() for struct member

        > What prompted the question?

        A code like the one I gave resulted in a crash. That's why I posted the
        question. My main point was if allocating and freeing memory is OK when
        done on a struct member (I knew it's OK, but the above crash made me a
        bit confused).

        I presume it's a compilation problem since the release build works and
        the crash happens for debug build (which is weird since it is usually
        the other way round).

        Comment

        • Alex Fraser

          #5
          Re: malloc() for struct member

          "googler" <pinaki_m77@yah oo.com> wrote in message
          news:1128579299 .236795.176820@ o13g2000cwo.goo glegroups.com.. .
          [snip][color=blue]
          > I presume it's a compilation problem since the release build works and
          > the crash happens for debug build (which is weird since it is usually
          > the other way round).[/color]

          I agree it is usually the other way round, but the same still applies: the
          difference is most likely due to undefined behaviour.

          Alex


          Comment

          • Flash Gordon

            #6
            Re: malloc() for struct member

            Alex Fraser wrote:[color=blue]
            > "googler" <pinaki_m77@yah oo.com> wrote in message
            > news:1128579299 .236795.176820@ o13g2000cwo.goo glegroups.com.. .
            > [snip]
            >[color=green]
            >>I presume it's a compilation problem since the release build works and
            >>the crash happens for debug build (which is weird since it is usually
            >>the other way round).[/color]
            >
            > I agree it is usually the other way round, but the same still applies: the
            > difference is most likely due to undefined behaviour.[/color]

            To expand on what Alex said (which I agree with), I would strongly
            suggest that you track down and fix the bug. It might not be causing a
            crash in the release build, but it could well be corrupting something
            under some conditions leading to incorrect results, for example raising
            millions of invoices for 139.90 instead of 149.90 and loosing some
            company lots of money. Or you might be lucky and it crashes on your
            customers instead of corrupting their vital data.
            --
            Flash Gordon
            Living in interesting times.
            Although my email address says spam, it is real and I read it.

            Comment

            • KJ

              #7
              Re: malloc() for struct member


              googler wrote:[color=blue]
              > Hello, I have a very simple question that I'm a bit confused about
              > right now. Is it OK to allocate memory by malloc() or calloc() for a
              > struct member and then call free() on it? For example, I have the code
              > below.
              >
              > struct mystruct {
              > int a;
              > char *b;
              > int c;
              > };
              >
              > struct mystruct myobject;
              >
              > myobject.b = (char *)malloc(50);[/color]
              As Every Body Said Not Need To Type Cast.[color=blue]
              > ...
              > ...
              > free(myobject.b );
              >
              > Is the above code OK, or is there any potential problem with it?[/color]
              The code doesn't seems to have problem. But since i m not sure the
              whole code is there or not so it could be some other reason.[color=blue]
              >
              > Thanks![/color]

              Comment

              • Kenneth Brody

                #8
                Re: malloc() for struct member

                googler wrote:[color=blue]
                >
                > Hello, I have a very simple question that I'm a bit confused about
                > right now. Is it OK to allocate memory by malloc() or calloc() for a
                > struct member and then call free() on it? For example, I have the code
                > below.
                >
                > struct mystruct {
                > int a;
                > char *b;
                > int c;
                > };
                >
                > struct mystruct myobject;
                >
                > myobject.b = (char *)malloc(50);
                > ...
                > ...
                > free(myobject.b );
                >
                > Is the above code OK, or is there any potential problem with it?[/color]

                The above is no different than:

                char *b;
                ...
                b = malloc(50);
                ...
                free(b);

                (Aside from the removal of the unnecessary, and sometimes problematic,
                cast of malloc's return.)

                The fact that the place you store the pointer is within a struct has
                no bearing on how malloc/free work.

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


                Comment

                • googler

                  #9
                  Re: malloc() for struct member

                  Thanks everybody for the help.
                  [color=blue][color=green]
                  > > myobject.b = (char *)malloc(50);[/color]
                  > As Every Body Said Not Need To Type Cast.[/color]

                  Doesn't K&R use type cast with malloc()? Maybe it's not a good
                  practice, but I'm wondering that in almost all C codes I've seen, type
                  cast has been used with malloc().

                  Comment

                  • Keith Thompson

                    #10
                    Re: malloc() for struct member

                    "googler" <pinaki_m77@yah oo.com> writes:[color=blue]
                    > Thanks everybody for the help.[color=green][color=darkred]
                    >> > myobject.b = (char *)malloc(50);[/color]
                    >> As Every Body Said Not Need To Type Cast.[/color]
                    >
                    > Doesn't K&R use type cast with malloc()? Maybe it's not a good
                    > practice, but I'm wondering that in almost all C codes I've seen, type
                    > cast has been used with malloc().[/color]

                    Yes, but the errata list at
                    <http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html> corrects it:

                    142(6.5, toward the end): The remark about casting the return
                    value of malloc ("the proper method is to declare ... then
                    explicitly coerce") needs to be rewritten. The example is correct
                    and works, but the advice is debatable in the context of the
                    1988-1989 ANSI/ISO standards. It's not necessary (given that
                    coercion of void * to ALMOSTANYTYPE * is automatic), and possibly
                    harmful if malloc, or a proxy for it, fails to be declared as
                    returning void *. The explicit cast can cover up an unintended
                    error. On the other hand, pre-ANSI, the cast was necessary, and it
                    is in C++ also.

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

                    • Baxter

                      #11
                      Re: malloc() for struct member

                      After you free the memory, set the member variable to NULL and see if that
                      changes anything.

                      When you start getting weird errors/crashes, it's usually worthwhile to look
                      for buffer overruns, freeing memory that has already been freed, and things
                      like that.

                      --
                      ---------------------------------------------------------------------
                      DataGet & PocketLog www.dataget.com
                      Data Collectors www.baxcode.com
                      --------------------------------------------------------------------



                      "googler" <pinaki_m77@yah oo.com> wrote in message
                      news:1128579299 .236795.176820@ o13g2000cwo.goo glegroups.com.. .[color=blue][color=green]
                      > > What prompted the question?[/color]
                      >
                      > A code like the one I gave resulted in a crash. That's why I posted the
                      > question. My main point was if allocating and freeing memory is OK when
                      > done on a struct member (I knew it's OK, but the above crash made me a
                      > bit confused).
                      >
                      > I presume it's a compilation problem since the release build works and
                      > the crash happens for debug build (which is weird since it is usually
                      > the other way round).
                      >[/color]


                      Comment

                      Working...