Skip to main content
Engineering LibreTexts

12.5: Freeing Memory

  • Page ID
    35860
  • Once you’re done using memory, you must return it to the free memory pool. If you don’t, no other application (nor the operating system) can use it. The memory will be effectively lost until the system is rebooted. This is known as a memory leak. To return memory that you have no further use for, use free(). Here is the prototype:

    int free( void *p );
    

    p is the pointer that you initially received from either malloc() or calloc(). The return value of the free() function is 0 for success or −1 on error. Normally this function never fails if it is given a valid pointer. If it does fail, there is little that you can do about it (at least not at this level). Remember: Every block that you allocate eventually must be freed! You might wonder why the free() function does not need to know the size of the block to free. This is because along with the memory they pass to you, malloc() and calloc() actually allocate a little bit more for use by the operating system. In this extra memory that you don’t see are stored items such as the size of the block. This saves you a little house keeping work.