Thread: How to free memory in this program

  1. #1
    Coconut
    Guest

    How to free memory in this program

    Hi all,
    I have a hard time to determine where I appropriately free the allocated memory on the heap for 2Dim array below:

    Code:
    
    int main()
    {
       int **TwoDimPtr;
     
       TwoDimPtr = Create2DimArr(ROW, COL);
    
       /* Do some processing with 2D array here and then free its memory*/
       
    /* free the allocated memory here?? */
       free Creat2DimArr(ROW, COL);
    
       return 1;
    }
    
    int **Create2DimArr(row, col)
    {
       int r;
       int **twoDimArr = malloc(row * sizeof(int *));
       for (r=0; r<row; r++)
            twoDimArr[r] = malloc(col * sizeof(int));
    
       return twoDimArr;
        
       /* and reclaim memory from the heap here, right? */
        free(twoDimArr);
      
    }
    Your help would highly respected and appreciated.

    Coconut

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    Okay lets get one thing straight. When you call your function Create2DimArr( ) you have:

    return twoDimArr;

    Right when you reach this line the control goes back to main and assigns your pointer you have there. Your free( ) call after the return statement will never be reached. You can try putting a breakpoint there to double check this.

    Now, you assign a pointer to a pointer to TwoDimPtr defined in main( ). So now TwoDimPtr points to the location in memory you allocated in your function. So the appropriate thing to do is to free this before your program exits, in main. Hope this helps.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. Client-server system with input from separate program
    By robot-ic in forum Networking/Device Communication
    Replies: 3
    Last Post: 01-16-2009, 03:30 PM
  3. Novice Pointers/Class Question
    By C++Gamer in forum C++ Programming
    Replies: 8
    Last Post: 06-28-2006, 05:36 PM
  4. my C++ program hangs during memory deallocation.
    By the-tzar in forum C++ Programming
    Replies: 6
    Last Post: 03-06-2004, 10:39 AM
  5. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM