Type-casting void pointers?

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

    #16
    Re: Type-casting void pointers?

    Keith Thompson <kst-u@mib.org> writes:[color=blue]
    > Chris Croughton <chris@keristor .net> writes:
    > [...][color=green]
    >> In particular, I've never come across any case in professional
    >> programming where casting malloc() (or other void pointer) actually
    >> masked a failure to declare it or include the relevant header file,
    >> whereas I have come across cases where:
    >>
    >> pointer = (my_type*) malloc(sizeof(m y_type));
    >>
    >> correctly pointed out that the type of the pointer was not the same as
    >> expected, whereas just assigning the void pointer wouldn't have created
    >> any diagnostic at all.[/color]
    >
    > Which is why the recommended idiom is
    >
    > pointer = malloc(sizeof *pointer);[/color]

    Following up to myself ...

    On the other hand, the cast could conceivably reveal the error that
    "pointer" should be of type my_type, but is actually of type
    some_other_type . This assumes that the correct type is more obvious
    in the context of the malloc() call than at the point of declaration.
    I still think it's more likely to mask an error than to reveal one.

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

    • Alexei A. Frounze

      #17
      Re: Type-casting void pointers?

      "Tim Woodall" <devnull@woodal l.me.uk> wrote in message
      ....[color=blue]
      > --
      > God said, "div D = rho, div B = 0, curl E = - @B/@t, curl H = J + @D/@t,"
      > and there was light.[/color]

      Wasn't that Maxwell? :) And obviosly, someone had to throw a few particles
      in to start things rolling.
      Alex
      P.S. there had been a mathematician before Maxwell to come up with those
      equations.


      Comment

      • Tim Rentsch

        #18
        Re: Type-casting void pointers?

        Richard Heathfield <invalid@addres s.co.uk.invalid > writes:
        [color=blue]
        > CBFalconer wrote:
        >[color=green]
        > > If a warning appears it is because it is needed.[/color]
        >
        > Would that that were the case! Some compilers diagnose perfectly good,
        > idiomatic, ordinary C code. Grrr.[/color]

        Well said. *applause*

        Comment

        • Old Wolf

          #19
          Re: Type-casting void pointers?

          Chris Croughton wrote:[color=blue]
          > Richard Heathfield <invalid@addres s.co.uk.invalid > wrote:[color=green]
          >> Writing bad code to avoid lousy warnings is a lousy idea. Sometimes,
          >> we do it anyway, I know - but we should do so in the full knowledge
          >> that it's a lousy idea, and we should feel guilty for weeks
          >> afterwards. Or even months.[/color]
          >
          > I do, but it's a job requirement (specifically, we don't get to choose
          > the compiler, that's determined by what the customer is using, and
          > delivering code with hundreds of warnings is not good for business).[/color]

          Out of interest, which compilers do warn about correct usage of
          malloc?
          [color=blue][color=green][color=darkred]
          >>> If a warning appears it is because it is needed.[/color]
          >> Would that that were the case! Some compilers diagnose perfectly
          >> good, idiomatic, ordinary C code. Grrr.[/color][/color]

          The worst I've seen is a warning when you cast something to
          the same type it already was. For example:

          isprint( (unsigned char)ch );

          If you compile with plain char unsigned, it will warn about this
          cast.

          It gets really annoying in macros, where you often put in casts
          because the macro could really be called with any integral type,
          and then this compiler would warn when you use the one type that
          matches the cast.

          It was possible to turn off this warning, but not without also
          turning off important warnings. :X
          [color=blue]
          > In particular, I've never come across any case in professional
          > programming where casting malloc() (or other void pointer) actually
          > masked a failure to declare it or include the relevant header file,[/color]

          How many platforms have you programmed on where int, size_t,
          and void* are not interchangeable , and the compiler does not
          have special recognition of standard library functions?
          [color=blue]
          > whereas I have come across cases where:
          >
          > pointer = (my_type*) malloc(sizeof(m y_type));
          >
          > correctly pointed out that the type of the pointer was not the
          > same as expected, whereas just assigning the void pointer wouldn't
          > have created any diagnostic at all.[/color]

          There would not have been any diagnostic in either case, if the
          parameter to malloc were wrong, ie.

          pointer = (correct_type*) malloc(sizeof(m y_type));

          So this is a bit of a Pascal's wager.

          Note that this problem can be eschewed with:

          malloc(sizeof *ptr);

          Comment

          • Keith Thompson

            #20
            Re: Type-casting void pointers?

            "Old Wolf" <oldwolf@inspir e.net.nz> writes:
            [...][color=blue]
            > The worst I've seen is a warning when you cast something to
            > the same type it already was. For example:
            >
            > isprint( (unsigned char)ch );
            >
            > If you compile with plain char unsigned, it will warn about this
            > cast.[/color]

            Even worse, plain char and unsigned char are distinct types, even if
            plain char happens to be unsigned. If the compiler complains that the
            cast is unnecessary, I can see the point. If it complains that the
            argument is of the same type specified in the cast, it's just 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

            • Christian Bau

              #21
              Re: Type-casting void pointers?

              In article <kfnhdetqlux.fs f@alumnus.calte ch.edu>,
              Tim Rentsch <txr@alumnus.ca ltech.edu> wrote:
              [color=blue]
              > Richard Heathfield <invalid@addres s.co.uk.invalid > writes:
              >[color=green]
              > > CBFalconer wrote:
              > >[color=darkred]
              > > > If a warning appears it is because it is needed.[/color]
              > >
              > > Would that that were the case! Some compilers diagnose perfectly good,
              > > idiomatic, ordinary C code. Grrr.[/color]
              >
              > Well said. *applause*[/color]

              Example for _really_ stupid warnings:

              unsigned char f (int x) { return (x > 0); }

              gives a warning on brain-damaged compilers because (x > 0) has type int,
              and conversion from int to unsigned char is not always value conserving,
              BUT (x > 0) has a value of 0 or 1 and will be converted without problems.

              char f (int x) { return x ? 'y' : 'n'; }

              Same problem here; the result of (x ? 'y' : 'n') is of type int, but the
              actual result can always be converted to char without problems.

              Comment

              • Chris Croughton

                #22
                Re: Type-casting void pointers?

                On 17 Jul 2005 14:02:13 -0700, Old Wolf
                <oldwolf@inspir e.net.nz> wrote:
                [color=blue]
                > Chris Croughton wrote:[color=green]
                >> Richard Heathfield <invalid@addres s.co.uk.invalid > wrote:[color=darkred]
                >>> Writing bad code to avoid lousy warnings is a lousy idea. Sometimes,
                >>> we do it anyway, I know - but we should do so in the full knowledge
                >>> that it's a lousy idea, and we should feel guilty for weeks
                >>> afterwards. Or even months.[/color]
                >>
                >> I do, but it's a job requirement (specifically, we don't get to choose
                >> the compiler, that's determined by what the customer is using, and
                >> delivering code with hundreds of warnings is not good for business).[/color]
                >
                > Out of interest, which compilers do warn about correct usage of
                > malloc?[/color]

                You mean assigning void* to a pointer to non-void? At least one I've
                used (could have been the IAR H8 series compiler, but I wouldn't
                guarantee it).
                [color=blue][color=green][color=darkred]
                >>>> If a warning appears it is because it is needed.
                >>> Would that that were the case! Some compilers diagnose perfectly
                >>> good, idiomatic, ordinary C code. Grrr.[/color][/color]
                >
                > The worst I've seen is a warning when you cast something to
                > the same type it already was. For example:
                >
                > isprint( (unsigned char)ch );
                >
                > If you compile with plain char unsigned, it will warn about this
                > cast.[/color]

                Try things like:

                unsigned char ch;
                int in;
                in = getc(stdin);
                if (in != EOF)
                ch = in;

                On some of the ARM compilers it gives a warning:

                conversion from 'int ' to 'unsigned char ', possible loss of data
                [color=blue]
                > It gets really annoying in macros, where you often put in casts
                > because the macro could really be called with any integral type,
                > and then this compiler would warn when you use the one type that
                > matches the cast.
                >
                > It was possible to turn off this warning, but not without also
                > turning off important warnings. :X[/color]

                Exactly. And the 'silly' warnings can mask the real ones (and even mask
                the rrors, I've had occasions where it's taken me a lot of time even to
                find the error message knowing that there is one, because it's been lost
                in the 'noise' of the spurious warnings).
                [color=blue][color=green]
                >> In particular, I've never come across any case in professional
                >> programming where casting malloc() (or other void pointer) actually
                >> masked a failure to declare it or include the relevant header file,[/color]
                >
                > How many platforms have you programmed on where int, size_t,
                > and void* are not interchangeable , and the compiler does not
                > have special recognition of standard library functions?[/color]

                Lots. Including (but not limited to, these are only the ones which I
                remember definitely had different sizes for at least one of those
                types):

                Z8000
                M68000
                H8 family
                80x86

                The only "special recognition" by the compilers has been when the
                appropriate header -- and therefore the appropriate prototype -- has
                been included.

                I haven't programmed for a C compiler where int and void* were
                interchangeable without a cast since I left university where we had a
                pre-K&R compiler (thinking of it, I don't think it had void at all so
                they weren't interchangeable then either).
                [color=blue][color=green]
                >> whereas I have come across cases where:
                >>
                >> pointer = (my_type*) malloc(sizeof(m y_type));
                >>
                >> correctly pointed out that the type of the pointer was not the
                >> same as expected, whereas just assigning the void pointer wouldn't
                >> have created any diagnostic at all.[/color]
                >
                > There would not have been any diagnostic in either case, if the
                > parameter to malloc were wrong, ie.
                >
                > pointer = (correct_type*) malloc(sizeof(m y_type));[/color]

                True. Easier is to do something like:

                #define NEW(t) ((T*)malloc(siz eof(T)))

                and then

                int *p = NEW(char);

                gives a diagnostic (usually an error, occasionally a warning).
                [color=blue]
                > So this is a bit of a Pascal's wager.
                >
                > Note that this problem can be eschewed with:
                >
                > malloc(sizeof *ptr);[/color]

                But that doesn't catch the case where you know what the type should be
                and you want to ensure that the pointer is the correct type.

                Chris C

                Comment

                • hugo2

                  #23
                  Re: Type-casting void pointers?



                  Stephan Hoffmann wrote:
                  [color=blue]
                  >
                  > I think some compilers give a warning without the explicit cast.
                  > Maybe the author wanted to write 'warning-free' code.
                  >
                  > Stephan[/color]

                  hugo July 17
                  Ah! I too had a feeling the casts were not
                  strickly needed, but were for 'portablitiy'
                  reasons.
                  Portability issues are very murky waters
                  to me, and I don't dive by myself.

                  Comment

                  • hugo2

                    #24
                    Re: Type-casting void pointers?



                    pete wrote:[color=blue]
                    >hugo wrote:[color=green]
                    > > The addresses are all unsigned int.[/color]
                    >
                    > What do you mean by that?
                    > I don't see any code about "unsigned int".
                    > "byte" either means "unsigned char" or the definition is wrong.
                    > memcpy works on objects of all types.[/color]

                    hugo July 18
                    As far as I know, addresses are memory locations
                    and are always integers. Negative or fractional
                    addresses don't make any sense, do they?
                    So the addresses are all positive integers,
                    and that is what is being assigned to pbTo
                    and pbFrom to initalize them.

                    That is what I ment.

                    The 'byte' type is a data type, which I
                    assumed to have some meaning either in
                    a header file or a program typedef.
                    Maguire did not explain it.

                    hugo.

                    Comment

                    • Keith Thompson

                      #25
                      Re: Type-casting void pointers?

                      "hugo2" <obrhy8@yahoo.c om> writes:[color=blue]
                      > pete wrote:[color=green]
                      >>hugo wrote:[color=darkred]
                      >> > The addresses are all unsigned int.[/color]
                      >>
                      >> What do you mean by that?
                      >> I don't see any code about "unsigned int".
                      >> "byte" either means "unsigned char" or the definition is wrong.
                      >> memcpy works on objects of all types.[/color]
                      >
                      > hugo July 18
                      > As far as I know, addresses are memory locations
                      > and are always integers. Negative or fractional
                      > addresses don't make any sense, do they?
                      > So the addresses are all positive integers,
                      > and that is what is being assigned to pbTo
                      > and pbFrom to initalize them.[/color]

                      No. Addresses are addresses. The language defines conversions
                      between addresses (pointers) and integers, but it says very little
                      about what those conversions do. Basically, if you convert an address
                      value to an integer big enough to hold it, then convert it back to the
                      pointer type, you'll get the original value -- but the intermediate
                      integer value may be completely meaningless.

                      It happens that, on many actual systems, addresses look a lot like
                      unsigned integers, but that's an implementation detail.

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

                      • CBFalconer

                        #26
                        Re: Type-casting void pointers?

                        hugo2 wrote:[color=blue]
                        > pete wrote:[color=green]
                        >> hugo wrote:[/color]
                        >[color=green][color=darkred]
                        >>> The addresses are all unsigned int.[/color]
                        >>
                        >> What do you mean by that? I don't see any code about "unsigned
                        >> int". "byte" either means "unsigned char" or the definition is
                        >> wrong. memcpy works on objects of all types.[/color]
                        >
                        > As far as I know, addresses are memory locations and are always
                        > integers. Negative or fractional addresses don't make any sense,
                        > do they? So the addresses are all positive integers, and that is
                        > what is being assigned to pbTo and pbFrom to initalize them.[/color]

                        You are surrounded all day by addresses that are not integers. For
                        example, "1234 W Foo St, Bar, State of Fee, Foe". What makes you
                        think computers have to linearize their addresses? Some of them
                        are so linearized, such as which memory chip, L2 Cache or main
                        memory or virtual memory. But down under that layer the
                        differences still exist.

                        --
                        "If you want to post a followup via groups.google.c om, don't use
                        the broken "Reply" link at the bottom of the article. Click on
                        "show options" at the top of the article, then click on the
                        "Reply" at the bottom of the article headers." - Keith Thompson


                        Comment

                        Working...