Test if pointer points to allocated memory

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

    #1

    Test if pointer points to allocated memory

    Is there anyway to test if a pointer points to allocated memory or
    not?
    For example if I have a pointer such as char *p is there a standard
    way to test whether an assignment such as the following has been
    applied?
    p = (char *) malloc(sizeof(c har) * n);
  • Joona I Palaste

    #2
    Re: Test if pointer points to allocated memory

    Andrew <andrew.zdenek@ ca.com> scribbled the following:[color=blue]
    > Is there anyway to test if a pointer points to allocated memory or
    > not?
    > For example if I have a pointer such as char *p is there a standard
    > way to test whether an assignment such as the following has been
    > applied?
    > p = (char *) malloc(sizeof(c har) * n);[/color]

    Not portably.

    --
    /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
    \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
    "Outside of a dog, a book is a man's best friend. Inside a dog, it's too dark
    to read anyway."
    - Groucho Marx

    Comment

    • pete

      #3
      Re: Test if pointer points to allocated memory

      Andrew wrote:[color=blue]
      >
      > Is there anyway to test if a pointer points to allocated memory or
      > not?
      > For example if I have a pointer such as char *p is there a standard
      > way to test whether an assignment such as the following has been
      > applied?
      > p = (char *) malloc(sizeof(c har) * n);[/color]

      If a pointer is uninitialized or has been freed
      without being reassigned, then you can't evaluate the pointer.

      If you know that a pointer value is either NULL or
      points to memory, you can check for NULL.

      I think you could just add another object to keep
      track of if that line was executed.

      int applied = 0;

      p = (char *) malloc(sizeof(c har) * n);
      applied = 1;

      I also suspect that you have a question about the
      return value of malloc, but I'm not sure.

      After a malloc assignment has been made,
      you always need to check for NULL.

      p = malloc(n * sizeof *p);
      if (p == NULL) {
      /* deal with it intelligently */
      }

      --
      pete

      Comment

      • CBFalconer

        #4
        Re: Test if pointer points to allocated memory

        Andrew wrote:[color=blue]
        >
        > Is there anyway to test if a pointer points to allocated memory or
        > not?
        > For example if I have a pointer such as char *p is there a standard
        > way to test whether an assignment such as the following has been
        > applied?
        > p = (char *) malloc(sizeof(c har) * n);[/color]

        Don't cast malloc. It is unnecessary and hides errors.

        To all practical purposes, your answer is no. However if you
        execute "free(p);" and the program goes BOOM you can be fairly
        sure that p was not malloced, or has already been freed. I'm sure
        this is a great help and comfort to you.

        --
        Chuck F (cbfalconer@yah oo.com) (cbfalconer@wor ldnet.att.net)
        Available for consulting/temporary embedded and systems.
        <http://cbfalconer.home .att.net> USE worldnet address!


        Comment

        • Dan Pop

          #5
          Re: Test if pointer points to allocated memory

          In <6536dc17.04012 10825.54283155@ posting.google. com> andrew.zdenek@c a.com (Andrew) writes:
          [color=blue]
          >Is there anyway to test if a pointer points to allocated memory or
          >not?
          >For example if I have a pointer such as char *p is there a standard
          >way to test whether an assignment such as the following has been
          >applied?
          >p = (char *) malloc(sizeof(c har) * n);[/color]

          If the pointer has not yet been initialised or if it points to memory
          that has been already freed, you're not even allowed to evaluate it in
          a portable C program.

          In a well designed program, you don't need such a check: you should
          know whether it is initialised or not. The alternative takes a lot of
          programming discipline: initialise each pointer with NULL at the point of
          definition and reset it to NULL as soon as the object it used to point to
          no longer exists (or is about to disappear). You may find the
          following macro useful for this purpose:

          #define FREE(p) (free(p), p = NULL)

          but it is far from solving the problem, because there may be other
          pointers pointing into the block being free'd. But malloc and friends
          are not the full story. Consider:

          char *global;

          void foo(void)
          {
          char buff[100];
          global = buff;
          ...
          }

          You need a "global = NULL;" before returning from foo(), because the life
          of buff ends at that point.

          So, if you're *extremely* careful, you can always use p != NULL to tell
          whether p is pointing to some object or not (bugs caused by omitting to
          reset a pointer can be very difficult to track). IMHO, it's much easier
          to avoid the need of such checks in the first place.

          Dan
          --
          Dan Pop
          DESY Zeuthen, RZ group
          Email: Dan.Pop@ifh.de

          Comment

          • Fred L. Kleinschmidt

            #6
            Re: Test if pointer points to allocated memory



            Andrew wrote:[color=blue]
            >
            > Is there anyway to test if a pointer points to allocated memory or
            > not?
            > For example if I have a pointer such as char *p is there a standard
            > way to test whether an assignment such as the following has been
            > applied?
            > p = (char *) malloc(sizeof(c har) * n);[/color]

            Other answers to this post address the pointer being set to malloc'd
            memory.
            But even if you are very careful to initialize all pointers to NULL, and
            re-set them to NULL when you free allocated memory, you can never be
            sure a non-NULL pointer points to allocated memory - it may point to
            some static or heap string:

            static char hello[] = "Hello";
            char *p = NULL;
            ....
            p = hello;

            If you later test p for non-NULL in order to determine whether to free
            it, you will be in big trouble.
            --
            Fred L. Kleinschmidt
            Boeing Associate Technical Fellow
            Technical Architect, Common User Interface Services
            M/S 2R-94 (206)544-5225

            Comment

            • Sean Kenwrick

              #7
              Re: Test if pointer points to allocated memory


              "Andrew" <andrew.zdenek@ ca.com> wrote in message
              news:6536dc17.0 401210825.54283 155@posting.goo gle.com...[color=blue]
              > Is there anyway to test if a pointer points to allocated memory or
              > not?
              > For example if I have a pointer such as char *p is there a standard
              > way to test whether an assignment such as the following has been
              > applied?
              > p = (char *) malloc(sizeof(c har) * n);[/color]

              You could try realloc(char * ptr,size) to try and reallocate the memory the
              pointer is referencing. Although it is not clear whether realloc() will fail
              gracefully (E.g. by returning NULL) or whether it will crash your
              application if it is not a valid pointer - I suppose this depends on the
              implementation. Its a long shot but its your only hope....

              Sean


              Comment

              • CBFalconer

                #8
                Re: Test if pointer points to allocated memory

                Sean Kenwrick wrote:[color=blue]
                > "Andrew" <andrew.zdenek@ ca.com> wrote in message
                >[color=green]
                > > Is there anyway to test if a pointer points to allocated memory
                > > or not? For example if I have a pointer such as char *p is there
                > > a standard way to test whether an assignment such as the
                > > following has been applied?
                > >
                > > p = (char *) malloc(sizeof(c har) * n);[/color]
                >
                > You could try realloc(char * ptr,size) to try and reallocate the
                > memory the pointer is referencing. Although it is not clear whether
                > realloc() will fail gracefully (E.g. by returning NULL) or ..snip..[/color]

                It is clearly undefined behaviour leading to frisky nasal demons.

                --
                Chuck F (cbfalconer@yah oo.com) (cbfalconer@wor ldnet.att.net)
                Available for consulting/temporary embedded and systems.
                <http://cbfalconer.home .att.net> USE worldnet address!


                Comment

                • E. Robert Tisdale

                  #9
                  Re: Test if pointer points to allocated memory

                  Andrew wrote:
                  [color=blue]
                  > Is there anyway to test
                  > if a pointer points to allocated memory or not?
                  > For example, if I have a pointer such as char *p
                  > is there a standard way to test whether an assignment
                  > such as the following has been applied?[/color]
                  [color=blue]
                  > char* p = (char*)malloc(s izeof(char)*n);[/color]

                  if (p > (char*)(&p)) {
                  // p probably points to a character in automatic storage
                  // (the program stack)
                  }
                  else {
                  // p probably points to static data or free storage
                  }

                  But, of course, the ANSI/ISO C standards do *not* specify this.

                  Comment

                  • Jack Klein

                    #10
                    Re: Test if pointer points to allocated memory

                    On Wed, 21 Jan 2004 19:17:17 -0800, "E. Robert Tisdale"
                    <E.Robert.Tisda le@jpl.nasa.gov > wrote in comp.lang.c:
                    [color=blue]
                    > Andrew wrote:
                    >[color=green]
                    > > Is there anyway to test
                    > > if a pointer points to allocated memory or not?
                    > > For example, if I have a pointer such as char *p
                    > > is there a standard way to test whether an assignment
                    > > such as the following has been applied?[/color]
                    >[color=green]
                    > > char* p = (char*)malloc(s izeof(char)*n);[/color]
                    >
                    > if (p > (char*)(&p)) {[/color]

                    Undefined behavior. p and &p are not pointers to the same object or
                    one past the same object or array.
                    [color=blue]
                    > // p probably points to a character in automatic storage
                    > // (the program stack)[/color]

                    Not all processors have a stack. Even for those that do, you are
                    making the unwarranted and unproven assumption that "the stack"
                    resides at higher memory addresses than other areas. I know of
                    several architectures where processor hardware requires that the stack
                    be in low memory.
                    [color=blue]
                    > }
                    > else {
                    > // p probably points to static data or free storage
                    > }[/color]

                    Or is uninitialized. Or null. Or points to allocated memory that has
                    been free.
                    [color=blue]
                    > But, of course, the ANSI/ISO C standards do *not* specify this.[/color]

                    Neither does anyone with any sense, you included.

                    --
                    Jack Klein
                    Home: http://JK-Technology.Com
                    FAQs for
                    comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
                    comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                    alt.comp.lang.l earn.c-c++

                    Comment

                    • E. Robert Tisdale

                      #11
                      Re: Test if pointer points to allocated memory

                      Jack Klein wrote:
                      [color=blue]
                      > E. Robert Tisdale wrote:
                      >
                      > Undefined behavior.
                      > p and &p are not pointers to the same object
                      > or one past the same object or array.[/color]

                      Please elaborate. Why does that make a difference?
                      [color=blue]
                      >
                      >[color=green]
                      >> // p probably points to a character in automatic storage
                      >> // (the program stack)[/color]
                      >
                      > Not all processors have a stack.[/color]

                      But they all have "automatic storage".
                      The typical implementation of automatic storage is on the program stack.
                      [color=blue]
                      > Even for those that do, you are
                      > you are making the unwarranted and unproven assumption that
                      > "the stack" resides at higher memory addresses than other areas.
                      > I know of several architectures
                      > where processor hardware requires that the stack be in low memory.[/color]

                      Name one.
                      [color=blue][color=green]
                      >> }
                      >> else {
                      >> // p probably points to static data or free storage
                      >> }[/color]
                      >
                      > Or is uninitialized. Or null.
                      > Or points to allocated memory that has been free.
                      >[color=green]
                      >>But, of course, the ANSI/ISO C standards do *not* specify this.[/color]
                      >
                      > Neither does anyone with any sense, you included.[/color]

                      I don't know whether I have any sense or not.
                      But my assertion is easily tested:
                      [color=blue]
                      > cat main.c[/color]
                      #include <stdio.h>
                      #include <stdlib.h>

                      int main(int argc, char* argv[]) {
                      //char c;
                      //char* p = &c;
                      char* p = (char*)malloc(s izeof(char));
                      if (p > (char*)(&p)) {
                      fprintf(stdout, "p probably points to a character "
                      "in automatic storage.\n");
                      }
                      else {
                      fprintf(stdout, "p probably points to static data "
                      "or free storage.\n");
                      }
                      return 0;
                      }


                      Comment

                      • Jack Klein

                        #12
                        Re: Test if pointer points to allocated memory

                        On Wed, 21 Jan 2004 21:27:17 -0800, "E. Robert Tisdale"
                        <E.Robert.Tisda le@jpl.nasa.gov > wrote in comp.lang.c:
                        [color=blue]
                        > Jack Klein wrote:
                        >[color=green]
                        > > E. Robert Tisdale wrote:
                        > >
                        > > Undefined behavior.
                        > > p and &p are not pointers to the same object
                        > > or one past the same object or array.[/color]
                        >
                        > Please elaborate. Why does that make a difference?[/color]

                        Paragraph 5 of ISO 9899:1999 section 6.5.8 "Relational operators", a
                        little thing that defines the standard C language:

                        <quote>
                        When two pointers are compared, the result depends on the relative
                        locations in the address space of the objects pointed to. If two
                        pointers to object or incomplete types both point to the same object,
                        or both point one past the last element of the same array object,
                        they compare equal. If the objects pointed to are members of the same
                        aggregate object, pointers to structure members declared later compare
                        greater than pointers to members declared earlier in the structure,
                        and pointers to array elements with larger subscript values compare
                        greater than pointers to elements of the same array with lower
                        subscript values. All pointers to members of the same union object
                        compare equal. If the expression P points to an element of an array
                        object and the expression Q points to the last element of the same
                        array object, the pointer expression Q+1 compares greater than
                        P. In all other cases, the behavior is undefined.
                        </quote>
                        [color=blue][color=green][color=darkred]
                        > >> // p probably points to a character in automatic storage
                        > >> // (the program stack)[/color]
                        > >
                        > > Not all processors have a stack.[/color]
                        >
                        > But they all have "automatic storage".
                        > The typical implementation of automatic storage is on the program stack.
                        >[color=green]
                        > > Even for those that do, you are
                        > > you are making the unwarranted and unproven assumption that
                        > > "the stack" resides at higher memory addresses than other areas.
                        > > I know of several architectures
                        > > where processor hardware requires that the stack be in low memory.[/color]
                        >
                        > Name one.[/color]

                        All 8051 processors, limited to lowest 256 8-bit bytes.

                        All Philips XA processors, limited to lowest 64K 8-bit bytes.

                        All Texas Instruments TMS320C28xx DSPs, limited to lowest 64K 16-bit
                        bytes.

                        Once you leave the common desktop behind, there are quite a few
                        hardware architectures that limit their hardware stack to specific
                        regions of memory for a variety of reasons.
                        [color=blue][color=green][color=darkred]
                        > >> }
                        > >> else {
                        > >> // p probably points to static data or free storage
                        > >> }[/color]
                        > >
                        > > Or is uninitialized. Or null.
                        > > Or points to allocated memory that has been free.
                        > >[color=darkred]
                        > >>But, of course, the ANSI/ISO C standards do *not* specify this.[/color]
                        > >
                        > > Neither does anyone with any sense, you included.[/color]
                        >
                        > I don't know whether I have any sense or not.
                        > But my assertion is easily tested:[/color]

                        All that proves is that the one implementation you know, from which
                        you probably formed the erroneous impression, works the way it works.
                        This says nothing at all about any other platform/implementation, or
                        what the language defines.
                        [color=blue]
                        >[color=green]
                        > > cat main.c[/color]
                        > #include <stdio.h>
                        > #include <stdlib.h>
                        >
                        > int main(int argc, char* argv[]) {
                        > //char c;
                        > //char* p = &c;
                        > char* p = (char*)malloc(s izeof(char));
                        > if (p > (char*)(&p)) {
                        > fprintf(stdout, "p probably points to a character "
                        > "in automatic storage.\n");
                        > }
                        > else {
                        > fprintf(stdout, "p probably points to static data "
                        > "or free storage.\n");
                        > }
                        > return 0;
                        > }
                        >[/color]

                        Actually it doesn't even prove that, since you neglected to show the
                        output of the program.

                        --
                        Jack Klein
                        Home: http://JK-Technology.Com
                        FAQs for
                        comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
                        comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                        alt.comp.lang.l earn.c-c++

                        Comment

                        • Richard Heathfield

                          #13
                          Re: Test if pointer points to allocated memory

                          E. Robert Tisdale wrote:
                          [color=blue]
                          > Jack Klein wrote:
                          >[color=green]
                          >> E. Robert Tisdale wrote:
                          >>
                          >> Undefined behavior.
                          >> p and &p are not pointers to the same object
                          >> or one past the same object or array.[/color]
                          >
                          > Please elaborate. Why does that make a difference?[/color]

                          Because the Standard defines the comparison of pointers very carefully, in
                          6.5.8, as follows:

                          5 When two pointers are compared, the result depends on the
                          relative locations in the address space of the objects
                          pointed to. If two pointers to object or incomplete types
                          both point to the same object, or both point one past the
                          last element of the same array object, they compare equal.
                          If the objects pointed to are members of the same aggregate
                          object, pointers to structure members declared later
                          compare greater than pointers to members declared earlier
                          in the structure, and pointers to array elements with
                          larger subscript values compare greater than pointers to
                          elements of the same array with lower subscript values. All
                          pointers to members of the same union object compare equal.
                          If the expression P points to an element of an array object
                          and the expression Q points to the last element of the same
                          array object, the pointer expression Q+1 compares greater
                          than P. In all other cases, the behavior is undefined.

                          <snip>
                          [color=blue]
                          > But my assertion is easily tested:
                          >[color=green]
                          > > cat main.c[/color]
                          > #include <stdio.h>
                          > #include <stdlib.h>
                          >
                          > int main(int argc, char* argv[]) {
                          > //char c;
                          > //char* p = &c;
                          > char* p = (char*)malloc(s izeof(char));[/color]

                          sizeof(char) is guaranteed to be 1. The cast is unnecessary.
                          [color=blue]
                          > if (p > (char*)(&p)) {[/color]

                          At this point, the program invokes undefined behaviour, and thus its output
                          cannot be trusted.

                          --
                          Richard Heathfield : binary@eton.pow ernet.co.uk
                          "Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
                          C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
                          K&R answers, C books, etc: http://users.powernet.co.uk/eton

                          Comment

                          • rahul dev

                            #14
                            Re: Test if pointer points to allocated memory

                            "E. Robert Tisdale" <E.Robert.Tisda le@jpl.nasa.gov > wrote in message news:<400F40BD. 3020307@jpl.nas a.gov>...[color=blue]
                            > Andrew wrote:
                            >[color=green]
                            > > Is there anyway to test
                            > > if a pointer points to allocated memory or not?
                            > > For example, if I have a pointer such as char *p
                            > > is there a standard way to test whether an assignment
                            > > such as the following has been applied?[/color]
                            >[color=green]
                            > > char* p = (char*)malloc(s izeof(char)*n);[/color]
                            >
                            > if (p > (char*)(&p)) {
                            > // p probably points to a character in automatic storage
                            > // (the program stack)
                            > }
                            > else {
                            > // p probably points to static data or free storage
                            > }
                            >
                            > But, of course, the ANSI/ISO C standards do *not* specify this.[/color]

                            malloc() library function uses brk() and sbrk() to increase the
                            address space of a process. sbrk() is a system call that ask
                            the kernel to allocate space at the end of "data segment" of
                            the process. So, the address returned by malloc() should always
                            be greater than the end of data segment.
                            Now, the end of data segment may be found by printing the address
                            of the symbol "end" or the address of the symbol "_end". These
                            symbols are defined with the appropriate values by the linker.
                            Or you may use "objdump" to find out the addresses of data segments
                            of your executable.

                            -rd

                            Comment

                            • Christian Bau

                              #15
                              Re: Test if pointer points to allocated memory

                              In article <400F5F35.30307 08@jpl.nasa.gov >,
                              "E. Robert Tisdale" <E.Robert.Tisda le@jpl.nasa.gov > wrote:
                              [color=blue]
                              > Jack Klein wrote:
                              >[color=green]
                              > > E. Robert Tisdale wrote:
                              > >
                              > > Undefined behavior.
                              > > p and &p are not pointers to the same object
                              > > or one past the same object or array.[/color]
                              >
                              > Please elaborate. Why does that make a difference?[/color]

                              Because the C Standard says it is undefined behavior.

                              Comment

                              Working...