Checking if memory has been dynamically allocated

This is a discussion on Checking if memory has been dynamically allocated within the C Programming forums, part of the General Programming Boards category; >Well, I would say just free() it either way. You're relying on undefined behavior. 7.20.3.2 ... If ptr is a ...

  1. #16
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Well, I would say just free() it either way.
    You're relying on undefined behavior.
    7.20.3.2

    ... If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
    There is no safe, portable way to determine if a pointer points to dynamic memory memory or not. Fix your design so that you aren't forced to perform such a test.
    My best code is written with the delete key.

  2. #17
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    It is your responsibility to know whether or not your memory has been dynamically allocated. One way around your problem is do not use malloc() at all. This way you know that every object or memory object that is created will be released with delete.


    I use this construct in COM as well so that I know every interface that is created is released as well. Throwing malloc() and new around willy nilly will get you into trouble. Unless you have some reservations about combining new with a C program, new is a much better way of allocating memory. Malloc() makes me cringe.

    I believe trying a free() on unallocated memory will result in the compiler yelling at you - it does with delete. Of course you could thwart this but I see no reason to purposely crash your code.

    Post what you are trying to do because I'm lost.
    Last edited by VirtualAce; 03-10-2004 at 10:45 AM.

  3. #18
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Bubba
    Unless you have some reservations about combining new with a C program, new is a much better way of allocating memory. Malloc() makes me cringe.
    Reservations? Oh, you mean reservations in the sense of it's no longer C meaning of reservations, right?

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #19
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    Yeah that would be it. But who cares unless its for a class or something.

  5. #20
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Originally posted by Bubba
    It is your responsibility to know whether or not your memory has been dynamically allocated. One way around your problem is do not use malloc() at all. This way you know that every object or memory object that is created will be released with delete.
    Oh? Only if you switch to new. Can you describe the difference between writing in C using malloc() and writing in C++ using new? I personally don't see a difference.

    Originally posted by Bubba
    new is a much better way of allocating memory. Malloc() makes me cringe.
    Why? What does malloc do that new doesn't? What does new do that malloc doesn't? How is malloc harder or dangerous? Please justify your statement.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  6. #21
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >What does malloc do that new doesn't?
    Confuse people more often.

    >What does new do that malloc doesn't?
    Call constructors.

    >How is malloc harder or dangerous?
    The arguments are apparently harder to get right, and nobody tries to cast the return of new...

    Of course, all of these arguments are only relevant in C++ where the fact that new and delete work with constructors and destructors properly while malloc and free do not is the overwhelming reason to use new and delete. Ignoring that, simplicity is the next big reason.

    >Please justify your statement.
    I wouldn't mind seeing Bubba's reasoning as well.
    My best code is written with the delete key.

  7. #22
    Registered User pinko_liberal's Avatar
    Join Date
    Oct 2001
    Posts
    284
    Originally posted by WaltP
    Why? What does malloc do that new doesn't? What does new do that malloc doesn't? How is malloc harder or dangerous? Please justify your statement. [/B]
    Lets hope you do not delete something created with malloc.
    The one who says it cannot be done should never interrupt the one who is doing it.

  8. #23
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317

    I am a total newbie but was just wondering if this suggessiont would work

    couldn't you just create a copy of the pointer address used in the memory allocation and then compare it later with the current pointer to see if the address's are equal.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  9. #24
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Originally posted by pinko_liberal
    Lets hope you do not delete something created with malloc.
    Why would I do that? malloc()/free() work together, as do new/delete. My question has nothing to do with using the wrong functions. It has to do with using malloc() vs. new.

    My question stands as asked.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  10. #25
    WDT
    WDT is offline
    Tha 1 Sick RAT
    Join Date
    Dec 2003
    Posts
    271

    Re: I am a total newbie but was just wondering if this suggessiont would work

    Originally posted by manofsteel972
    couldn't you just create a copy of the pointer address used in the memory allocation and then compare it later with the current pointer to see if the address's are equal.
    You can. But what if you went around creating lots of pointers before you ever attempt to free anything. I believe conservation of resource(s) is the aim of this person.

    Also whilst we're busying arguing about malloc/new, free/delete, Let's remember that they belong to two not so disimilar but fundamentally different environs; C++ = OOP and C = procedural (Yes I heard about objective C).
    A hundred Elephants can knock down the walls of a fortress... One diseased rat can kill everyone inside

  11. #26
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317

    How to spare resources

    THe only reason why I mentioned that is because the Heap is one contiguous section of memory and has a base address so if you can compare the pointers address to the RANGE of heap then you can determine it it came from the heap or not and thus if it was allocated dynamically or am i wrong?
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  12. #27
    WDT
    WDT is offline
    Tha 1 Sick RAT
    Join Date
    Dec 2003
    Posts
    271
    I'm not saying you're wrong. Just pointing out that we shouldn't loose site of the goal.
    A hundred Elephants can knock down the walls of a fortress... One diseased rat can kill everyone inside

  13. #28
    Registered User
    Join Date
    Mar 2004
    Posts
    536

    Re: How to spare resources

    Originally posted by manofsteel972
    THe only reason why I mentioned that is because the Heap is one contiguous section of memory and has a base address so if you can compare the pointers address to the RANGE of heap then you can determine it it came from the heap or not and thus if it was allocated dynamically or am i wrong?
    I never thought of that. How would you test that to see if it is a valid method?

    I personally think it is the programmer's responsibility to keep track of all malloc()ed memory. (Just my opionion.)

    If the programmer can't keep track of it, maybe the program should be re-architected.

  14. #29
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231

    Re: Re: How to spare resources

    >>How would you test that to see if it is a valid method?
    Through no standard means that I know of.

    >>I personally think it is the programmer's responsibility to keep track of all malloc()ed memory. (Just my opionion.)
    Your opinion, and a good few others too

    >>If the programmer can't keep track of it, maybe the program should be re-architected.
    ... and that's the correct answer too.

    Here's one way. Personally, I'd avoid using something like this, but I guess someone might find it useful.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef enum memorytypes { MT_DYNAMIC, MT_STATIC } memorytypes_t;
    
    typedef struct DATA
    {
      memorytypes_t MT;
      char *msg;
    } data_t;
    
    void foo(data_t *Data, int i)
    {
      char *p = "This is static";
      switch (i)
      {
        case 1:
          Data->msg = malloc(20);  /* Do some error checking! */
          strcpy (Data->msg, "This is dynamic");
          Data->MT = MT_DYNAMIC;
          break;
        default:
          Data->msg = p;
          Data->MT = MT_STATIC;
          break;
      }
    }
      
    int main(void)
    {
      data_t dt1, dt2;
      
      foo (&dt1, 1);
      foo (&dt2, 2);
      printf ("dt1 : %s\n", dt1.msg);
      printf ("dt2 : %s\n", dt2.msg);
      
      if (dt1.MT == MT_DYNAMIC)
      {
        printf ("freeing dt1 %p\n", (void*)dt1.msg);
        free (dt1.msg);
      }
      
      if (dt2.MT == MT_DYNAMIC)
      {
        printf ("freeing dt2 %p\n", (void*)dt2.msg);
        free (dt2.msg);
      }
      
      return(0);
    }
    
    
    /* Output
    
    dt1 : This is dynamic
    dt2 : This is static
    freeing dt1 00842934
    
    */
    I can't help but feel the whole malloc/new thing is going a tad off topic, as the OP is writing in pure C (with a touch of ASM? ) :
    Posted by Xzyx987X
    Well, I already commited myself to using pure C for this program. Is there perhaps a way to simulate a try/catch in C using ASM?
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamically allocating memory
    By rs07 in forum C Programming
    Replies: 6
    Last Post: 09-14-2008, 03:26 AM
  2. Dynamically allocated memory
    By ^xor in forum Linux Programming
    Replies: 9
    Last Post: 06-28-2005, 11:42 AM
  3. Checking if memory was successfuly allocated.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 04-13-2005, 07:12 AM
  4. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM
  5. deleting dynamically allocated memory...
    By heljy in forum C++ Programming
    Replies: 2
    Last Post: 09-08-2002, 11:40 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21