avoiding multiple free calls on dynamically allocated memory

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sdkumar00
    New Member
    • Apr 2010
    • 4

    avoiding multiple free calls on dynamically allocated memory

    How can we avoid/detect multiple free calls for a dynamically allocated memory.

    Code:
    void example() {
      int *a;
      a = (int *)malloc(10);
      free(a);
      free(a); //how can we detect/avoid multiple free calls
    }
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    Don't believe you can

    I don't believe there is a way to tell if a piece of memory has already been freed or not. It is up to the programmer to exercise good memory management.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Set the deleted pointer to 0.

      Calling free() with a zero pointer is OK.

      However, if you have another pointer containing the same address, then all bets are off unles tyou implement reference checking. Very hard in C but in C++ you can use a Handle class.

      The best thing is to run a profiler on your code after you think its working.

      Comment

      Working...