Will free() clean up this allocated memory?

This is a discussion on Will free() clean up this allocated memory? within the C Programming forums, part of the General Programming Boards category; I have some legacy code that I have a question about. A pointer to allocated memory is passed as a ...

  1. #1
    Registered User simguy's Avatar
    Join Date
    Jan 2007
    Location
    Dallas-Ft Worth, TX
    Posts
    10

    Will free() clean up this allocated memory?

    I have some legacy code that I have a question about. A pointer to allocated memory is passed as a parameter to a function. In the function, there is a declaration statement that creates a new pointer and assigns it the value of the allocated pointer. Will the free() statement actually free the allocated memory?

    Thanks.

    Code:
    void test(int *intptr)
    {
         int* newptr = intptr;
    
          .
          .
          .
          .
          free(newptr);
    }

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Yes. free() only cares about the value passed to it. It cannot possibly know which variable was holding the value, because it is passed the value.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User simguy's Avatar
    Join Date
    Jan 2007
    Location
    Dallas-Ft Worth, TX
    Posts
    10
    Thanks --- that was my interpretation also, but wanted a second opinion (or even a 3rd and 4th)

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,210
    At the risk of stating the obvious, the caller of your function should not use the argument it passes again, except to reassign it. For example;
    Code:
    void test(int *pointer)
    {
        int *newpointer = pointer;
       free(newpointer);
    
    }
    
    int main()
    {
         int *data = malloc(5*sizeof(int));
         test(data);
        data[2] = 42;     /* undefined behaviour as test() has effectively performed free(data) */
    }
    Creating a copy of a pointer (pointerA = pointerB) means that both pointers point at the same data. So freeing one, frees both.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Arrays and pointers to allocated memory
    By TriKri in forum C Programming
    Replies: 19
    Last Post: 07-23-2006, 10:52 AM
  2. Novice Pointers/Class Question
    By C++Gamer in forum C++ Programming
    Replies: 8
    Last Post: 06-28-2006, 05:36 PM
  3. Where are pointers allocated in memory?
    By sparks in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2005, 12:52 PM
  4. Dynamically allocated memory
    By ^xor in forum Linux Programming
    Replies: 9
    Last Post: 06-28-2005, 11:42 AM

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