Memory question

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

    Memory question


    Hi All,

    As per the standard what is the result of passing NULL to both malloc and free?

    Regards,
    Mohan.

    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.m oderated. First time posters: Do this! ]

    [ comp.std.c++ is moderated. To submit articles, try just posting with ]
    [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
    [ --- Please see the FAQ before posting. --- ]
    [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

  • Victor Bazarov

    #2
    Re: Memory question

    "Mohanasundaram " <mohanasundaram @msn.com> wrote...[color=blue]
    >
    > As per the standard what is the result of passing NULL to both malloc[/color]
    and free?

    'free' does nothing if you pass null pointer there. 'malloc' does not
    accept pointers.


    Comment

    • Ron Natalie

      #3
      Re: Memory question


      "Victor Bazarov" <v.Abazarov@com Acast.net> wrote in message news:XnTUb.1879 29$5V2.976067@a ttbi_s53...[color=blue]
      > "Mohanasundaram " <mohanasundaram @msn.com> wrote...[color=green]
      > >
      > > As per the standard what is the result of passing NULL to both malloc[/color]
      > and free?
      >
      > 'free' does nothing if you pass null pointer there. 'malloc' does not
      > accept pointers.
      >[/color]
      In C++ NULL isn't a pointer. Passing NULL to malloc is legal. However
      the return value is implementation defined. It may either return a null pointer
      or a unique (but non-derferencable) pointer value.

      You can't use NULL as the operand of new or delete.

      Comment

      • Alf P. Steinbach

        #4
        Re: Memory question

        On Fri, 6 Feb 2004 16:15:49 -0500, "Ron Natalie" <ron@sensor.com > wrote:
        [color=blue]
        >
        >"Victor Bazarov" <v.Abazarov@com Acast.net> wrote in message news:XnTUb.1879 29$5V2.976067@a ttbi_s53...[color=green]
        >> "Mohanasundaram " <mohanasundaram @msn.com> wrote...[color=darkred]
        >> >
        >> > As per the standard what is the result of passing NULL to both malloc[/color]
        >> and free?
        >>
        >> 'free' does nothing if you pass null pointer there. 'malloc' does not
        >> accept pointers.
        >>[/color]
        >In C++ NULL isn't a pointer. Passing NULL to malloc is legal. However
        >the return value is implementation defined. It may either return a null pointer
        >or a unique (but non-derferencable) pointer value.
        >
        >You can't use NULL as the operand of new or delete.[/color]

        You can pass a NULL pointer value to delete, but not directly; it needs
        to be typed as a pointer.

        In C++ literal 'NULL' as a token is equivalent to literal '0' as a token.

        Sorry to pick nits, but that statement was just too easy to misinterpret.

        Comment

        • Ron Natalie

          #5
          Re: Memory question


          "Alf P. Steinbach" <alfps@start.no > wrote in message news:402406a6.1 39970531@News.C IS.DFN.DE...[color=blue][color=green]
          >>[/color]
          > You can pass a NULL pointer value to delete, but not directly; it needs
          > to be typed as a pointer[/color]

          That was my point. NULL doesn't have pointer type, so it can't be passed
          to delete. It can be passed to malloc as it has an integral zero value.
          [color=blue]
          > In C++ literal 'NULL' as a token is equivalent to literal '0' as a token.
          >
          > Sorry to pick nits, but that statement was just too easy to misinterpret.[/color]

          To pick nits. NULL as a token is equivalent to NULL. It's required to be
          a macro evaluating to an integral constant expression of value 0. It could
          be anything like:

          #define NULL 0 // my favorite
          #define NULL (0L) // unfortunately also quite common

          // the following are legal but weird.
          #define NULL (!true)
          #define NULL '\0'
          #define NULL (5 - 4 - 1)*(34L)/true

          Comment

          • Steve Clamage

            #6
            Re: Memory question


            Mohanasundaram wrote:[color=blue]
            > Hi All,
            >
            > As per the standard what is the result of passing NULL to both malloc and free?
            >[/color]

            The rules in the C++ standard for malloc and free are the same as in C.

            The malloc function takes an integer argument representing size, not NULL, which
            is a null pointer constant.

            Assuming you meant malloc(0), the results depend on the implementation. An
            implementation is allowed always to return a null pointer, or to return a unique
            pointer if it can (it's possible to run out of address space). It cannot return
            a pointer to an existing object. Whatever the return, you are not allowed to
            dereference the pointer, because it need not point to allocated memory. (You
            asked for 0 bytes, after all.)

            I don't find anything in either standard that disallows always returning the
            same non-null address for malloc(0), as long as that address is not othewise used.

            The short answer is that malloc(0) is allowed, but you can't depend on doing
            much with the result. Allowing malloc(0) simplifies some algorithms.

            Passing a null pointer to free() is allowed, and has no net effect.

            The net result of these rules is that you can always call free (once) with the
            result you got from malloc.

            --
            Steve Clamage, stephen.clamage @sun.com


            [ See http://www.gotw.ca/resources/clcm.htm for info about ]
            [ comp.lang.c++.m oderated. First time posters: Do this! ]

            [ comp.std.c++ is moderated. To submit articles, try just posting with ]
            [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
            [ --- Please see the FAQ before posting. --- ]
            [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


            Comment

            • James Kuyper

              #7
              Re: Memory question


              Mohanasundaram wrote:[color=blue]
              >
              > Hi All,
              >
              > As per the standard what is the result of passing NULL to both malloc and free?[/color]

              In C, the behavior of malloc(NULL) depends upon your implementation.
              1. NULL can be an integer constant expression with a value of 0, in
              which case you've done the eqivalent of calling malloc(0). Per 7.20.3p1
              of the C standard:

              "If the size of the space requested is zero, the behavior is
              implementation defined: either a null pointer is returned, or the
              behavior is as if the size were some nonzero value, except that the
              returned pointer shall not be used to access an object."

              2. NULL can be an integer constant expression with a value of 0, cast to
              void* (this is not permitted in C++). In that case, malloc(NULL) is
              equivalent to malloc((void*)0 ), which in turn is equivalent to
              malloc((size_t) (void*)0). The result of (size_t)(void*) 0 is
              implementation-defined; it can be any valid size_t value. On a great
              many implementations , it will be 0, but there are real implementations
              where it might not be, and portable code should not count on that.

              free(NULL) is much simpler. Per 7.20.3.2p2 of the C standard: "If ptr is
              a null pointer, no action occurs.".

              The C++ standard incorporates by reference most of the C standard
              library's description. The only changes it makes are to specify that
              malloc() does not call ::operator new(), and free() does not call
              ::operator delete().

              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
              [ comp.lang.c++.m oderated. First time posters: Do this! ]

              [ comp.std.c++ is moderated. To submit articles, try just posting with ]
              [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
              [ --- Please see the FAQ before posting. --- ]
              [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


              Comment

              • Anubis

                #8
                Re: Memory question

                Ron Natalie wrote:[color=blue]
                > #define NULL 0 // my favorite
                > #define NULL (0L) // unfortunately also quite common
                >
                > // the following are legal but weird.
                > #define NULL (!true)
                > #define NULL '\0'
                > #define NULL (5 - 4 - 1)*(34L)/true[/color]

                I sometimes see

                #define NULL ((void*)0)

                --
                Anubis

                Comment

                • Alf P. Steinbach

                  #9
                  Re: Memory question

                  On Sun, 08 Feb 2004 01:50:27 +0100, Anubis <anubis@remov e-anti-spam-tags.genezys.ne t> wrote:
                  [color=blue]
                  >Ron Natalie wrote:[color=green]
                  >> #define NULL 0 // my favorite
                  >> #define NULL (0L) // unfortunately also quite common
                  >>
                  >> // the following are legal but weird.
                  >> #define NULL (!true)
                  >> #define NULL '\0'
                  >> #define NULL (5 - 4 - 1)*(34L)/true[/color]
                  >
                  >I sometimes see
                  >
                  >#define NULL ((void*)0)[/color]

                  In C, perhaps, not in C++.

                  Unless you have a _very_ old, non-conforming compiler.

                  It would be nice if C++ not only allowed that (which it doesn't) but
                  required it, so that certain errors could be detected, but alas...

                  Comment

                  • Dylan Nicholson

                    #10
                    Re: Memory question


                    Steve Clamage <Stephen.Clamag e@Sun.COM> wrote in message news:<c010pa$47 9$1@news1nwk.SF bay.Sun.COM>...[color=blue]
                    >
                    > The net result of these rules is that you can always call free (once) with the
                    > result you got from malloc.
                    >[/color]
                    So I take it MSVC 6's crash on:

                    char* x = new char[0];
                    delete [] x;

                    is most definitely non-compliant...?

                    Dylan


                    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                    [ comp.lang.c++.m oderated. First time posters: Do this! ]

                    [ comp.std.c++ is moderated. To submit articles, try just posting with ]
                    [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
                    [ --- Please see the FAQ before posting. --- ]
                    [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


                    Comment

                    • lawrence.jones@ugsplm.com

                      #11
                      Re: Memory question


                      In comp.std.c Steve Clamage <Stephen.Clamag e@sun.com> wrote:[color=blue]
                      >
                      > I don't find anything in either standard that disallows always returning the
                      > same non-null address for malloc(0), as long as that address is not othewise used.[/color]

                      C99 7.20.3:

                      If the size of the space requested is zero, the behavior is
                      implementation-defined: either a null pointer is returned, or
                      the behavior is as if the size were some nonzero value, except
                      that the returned pointer shall not be used to access an object.

                      C90 contained slightly different language that was more easily misread,
                      but the intent was the same.

                      -Larry Jones

                      It's either spectacular, unbelievable success, or crushing, hopeless
                      defeat! There is no middle ground! -- Calvin


                      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                      [ comp.lang.c++.m oderated. First time posters: Do this! ]

                      [ comp.std.c++ is moderated. To submit articles, try just posting with ]
                      [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
                      [ --- Please see the FAQ before posting. --- ]
                      [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


                      Comment

                      • Stephen Clamage

                        #12
                        Re: Memory question


                        On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), lawrence.jones@ ugsplm.com
                        wrote:
                        [color=blue]
                        >
                        >In comp.std.c Steve Clamage <Stephen.Clamag e@sun.com> wrote:[color=green]
                        >>
                        >> I don't find anything in either standard that disallows always returning the
                        >> same non-null address for malloc(0), as long as that address is not othewise used.[/color]
                        >
                        >C99 7.20.3:
                        >
                        > If the size of the space requested is zero, the behavior is
                        > implementation-defined: either a null pointer is returned, or
                        > the behavior is as if the size were some nonzero value, except
                        > that the returned pointer shall not be used to access an object.
                        >
                        >C90 contained slightly different language that was more easily misread,
                        >but the intent was the same.
                        >[/color]

                        Yes, and as I said, I don't see anything that prohibits always
                        returning the same non-null address.

                        Suppose the malloc/free implementation reserves one byte, malloc(0)
                        always returns the address of that byte, and free() of that address is
                        a no-op. I don't see any rule violation.
                        ---
                        Steve Clamage, stephen.clamage @sun.com


                        [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                        [ comp.lang.c++.m oderated. First time posters: Do this! ]

                        [ comp.std.c++ is moderated. To submit articles, try just posting with ]
                        [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
                        [ --- Please see the FAQ before posting. --- ]
                        [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


                        Comment

                        • Stephen Clamage

                          #13
                          Re: Memory question


                          On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), wizofaus@hotmai l.com (Dylan
                          Nicholson) wrote:
                          [color=blue]
                          >
                          >Steve Clamage <Stephen.Clamag e@Sun.COM> wrote in message news:<c010pa$47 9$1@news1nwk.SF bay.Sun.COM>...[color=green]
                          > >
                          > > The net result of these rules is that you can always call free (once) with the
                          > > result you got from malloc.
                          > >[/color]
                          >So I take it MSVC 6's crash on:
                          >
                          >char* x = new char[0];
                          >delete [] x;
                          >
                          >is most definitely non-compliant...?[/color]

                          Bear in mind the following differences:

                          A new-expression like
                          new T // T is some type
                          new T[size}
                          is a syntactical construct that causes memory to be allocated by the
                          memory allocation function associated with type T, followed by
                          contructor invocation(s) for the allocated object(s).

                          The C++ standard library contiains six different overloads of operator
                          new, a function that can be called explicitly to allocate raw memory.
                          You can also write your own overloads, and replace some of the default
                          versions. The rules are given in the C++ standard section 18.4.1 and
                          3.7.3. A new-expression invokes some version of operator new, as
                          explained in section 5.3.4.

                          C++ also inherits library functions malloc and free from C, which can
                          be called explicitly to manage raw storage. The C++ standard does not
                          require that malloc (or free) be used in the implementation of new (or
                          delete) expressions, or of operator new (or operator delete).

                          The code you show involves a new-expression and a delete-expression,
                          not direct calls to malloc or free.

                          I read section 5.3.4 to say that the expression
                          new T[0]
                          is ill-formed, for any type T. The standard requires a strictly
                          positive value for the constant-expression giving the array size. But
                          I tried a couple of compilers at full warning levels, and neither
                          complained about new char[0].

                          If the code is invalid, the standard imposes no requirements on the
                          behavior of the program. But it seems to me that an implemention
                          allowing the expression should also allow deleteing the pointer that
                          was returned.

                          Calling the operator new function explicitly is a different story,
                          however. The expression
                          operator new(0)
                          is valid. If the operation succeeds, it must return a unique address
                          for each call, which can be passed to the corresponding operator
                          delete().


                          ---
                          Steve Clamage, stephen.clamage @sun.com


                          [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                          [ comp.lang.c++.m oderated. First time posters: Do this! ]

                          [ comp.std.c++ is moderated. To submit articles, try just posting with ]
                          [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
                          [ --- Please see the FAQ before posting. --- ]
                          [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


                          Comment

                          • Ron Natalie

                            #14
                            Re: Memory question


                            "Anubis" <anubis@remov e-anti-spam-tags.genezys.ne t> wrote in message news:c0415e$f8p $2@apollon.grec .isp.9tel.net.. .
                            [color=blue]
                            >
                            > I sometimes see
                            >
                            > #define NULL ((void*)0)
                            >[/color]

                            Only on defective compilers. The above is not a null pointer constant in C++.

                            Comment

                            • Keith Thompson

                              #15
                              Re: Memory question


                              wizofaus@hotmai l.com (Dylan Nicholson) writes:[color=blue]
                              > Steve Clamage <Stephen.Clamag e@Sun.COM> wrote in message
                              > news:<c010pa$47 9$1@news1nwk.SF bay.Sun.COM>...[color=green]
                              > > The net result of these rules is that you can always call free
                              > > (once) with the result you got from malloc.
                              > >[/color]
                              > So I take it MSVC 6's crash on:
                              >
                              > char* x = new char[0];
                              > delete [] x;
                              >
                              > is most definitely non-compliant...?[/color]

                              I'm posting in comp.std.c. From that point of view, I'm not sure
                              whether crashing (at run-time?) on a syntax error is non-compliant.
                              As long as it generates a diagnostic during compilation, it's probably
                              all right.

                              As far as C++ is concerned, I don't know whether the delete []
                              operator follows the same rules as free(). I've redirected followups
                              to comp.lang.c++.

                              --
                              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                              San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
                              Schroedinger does Shakespeare: "To be *and* not to be"


                              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                              [ comp.lang.c++.m oderated. First time posters: Do this! ]

                              [ comp.std.c++ is moderated. To submit articles, try just posting with ]
                              [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.e du ]
                              [ --- Please see the FAQ before posting. --- ]
                              [ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

                              Comment

                              Working...