What is the purpose of the free() function?

Asked

Viewed 1,963 times

23

  • In which cases should it be used?
  • There is an alternative?
  • It is recommended to use?
  • 4

    If your system allocates memory dynamically (as 99.99% of programs do) then you need to release it when it is no longer needed. But it is always possible to program using only statically allocated variables... I’m not saying it’s a good idea, but there may be cases where this is the best way. Just out of curiosity, I’ve seen a system quite a lot complex developed this way - by ignorance rather than by choice, yes, but it fulfilled its purpose satisfactorily.

  • I’m from time that didn’t exist heap and did not need to free memory :) nor stack had. The code pre-allocated all memory needed before execution. You just made small Jobs that performed only one task, had no function. there was no operating system, only one program monitor. Well, when I started it was already more modern but I came to do old stuff like this.

  • @mgibsonbr Until a time ago the Objetive C also had manual memory management, in this case there was no escape you had to allocate each object, retain and release each reference of each pointer, to avoid memory Leaks and null pointers access. Today we have ARC, however in some cases some companies still choose not to use it (more for legacy code support) since activating it without removing all allocs and retain and release would give copying error. Sometimes it is a matter of necessity or company convention.

  • @ooredpurple I did not understand the relationship between what you said and my comment (if it was supposed to have relationship... :P). What I meant was that if there is no dynamic allocation, there is no dynamic release. Personally, I think it is perfectly possible to design a simple program - that "does one thing and does it well" - that can operate with fixed memory. Everything would depend on the purpose of the program and the types of data it handles. Again, it is not the most usual, I just raised a possibility...

  • @mgibsonbr just commented to exemplify some cases where we can not always escape from manual memory allocation (as well as its release), although we increasingly have automatic memory management methods that facilitate our lives.

  • Did any answer solve the question? Can you accept any?

Show 1 more comment

2 answers

28


What is

It is the function to dislocate memory allocated in heap (there explains why the heap is necessary). It is usually used in pairs (not necessarily directly) with malloc().

Recommending

In codes beyond the trivial has no way to avoid the use of malloc() (and his sisters calloc() and realloc(), so you can’t avoid using the free().

Where does the malloc() have to use the free(). Of course in things much simple may not use. It is wrong but will not cause problems. Even in simple things it is the good programmer’s habit to always do correct.

So you should always use it. There is no escape from it unless you want to compromise all the computer memory. Imagine that you allocate memory and always leave it there. If the application runs for some time and does something useful in a very short time many gigabytes of memory will be little for your application. A program generates a lot of junk (data that was needed at a time but are no longer).

When to use

One of the recommendations is to use both functions together within the same function to avoid getting lost and forget to dislocate, or worse, to dislocate what cannot yet and will still be used by the application.

Of course, this is not always possible. Then care needs to be redoubled. Documentation, caution and a lot of testing will be required.

In C++ this becomes even more complicated because even if it is in the same function, in the same scope an exception can be launched and divert the flow of the program without you knowing, and a call to the function free() or use of the operator delete may not be executed as expected. Hence a little more automatic management becomes critical.

Alternatives

The alternative is to use an automatic management. In the background this management will use the free() somehow since this function is used to communicate with the operating system API to free up memory.

Garbage Collector

In some cases this automatic management can be a Garbage Collector but it’s not usually used in C/C++ since the language doesn’t help. Moreover, it often changes the characteristics of the use of language by going against their culture.

Delete

In C++ there is even an alternative. It is actually recommended to use delete (that internally ends up using the free() but in a more organized way) and not the free() .

Actually in C++ o free() should be avoided in favour of the operator delete or even delete[] that desaloca arrays. The original C function is too crude for C++ standards. It can still be used, since it needs C compatibility, needs to communicate with the OS and in some cases greater flexibility may be required (very rare).

Smart pointers

Furthermore, it is recommended to leave the semi-automatic management using own classes to control the memory management. These classes do the allocation and know when they need it dislocate leaving the programmer free of this decision. These classes are called smart pointers. They help a lot but they don’t work miracles. If you forget to use them or use the wrong class for this you may get unwanted results.

Other language

If you don’t want to take care of memory management the alternative is to use a language with managed memory, as is more common nowadays. C/C++ should be used when you need the power, flexibility and speed of these languages. Often the choice of one of them is precisely to be able to manage the memory as you wish.

  • 1

    +10 for the last paragraph.

  • In C++ If You Do Not Use delete Memory Is Not Released ? And Also Not In C ?

  • While running the application it is not released until you command it. This is the advantage of these languages, you control how you want to use memory.

  • @bigown But After It Closes It Is Released Right ?

  • Yes. You are in my comment on the other reply http://answall.com/questions/43766/qual-a-finalitye-da-fun%C3%A7%C3%a3o-free/43770#comment87093_43769

16

The function void free(void *ptr) serves to free memory previously allocated by functions calloc, malloc, or realloc.

It shall be used in all cases where the use of a previously allocated memory space is no longer required.

I’d say it’s obligatory use. Not in the sense of not working, but in the sense of maintaining the integrity of your memory.

In language C access to memory is of utmost importance, if we do not have this worry will mess up for certain.

Note: Always keep in mind the memory allocation so that it does not allocate less memory than necessary for what you want. And always be extra careful to free up the memory space you no longer need.

  • 2

    Adding a case-by-case experience: I had close to 50% of the RAM used before I started using dynamically allocated memory with C. I didn’t use free to free up memory. After some uses, the PC’s memory was 80% used, as it was not released when the programs closed.

  • 2

    @Mutley: When a program closes the operating system it takes back all the memory it was using, regardless of whether the program gave free or not. The biggest problem is when you have a program that runs in the background without closing.

  • In the case of languages with garbage collector like Java, yes. but C/C++ doesn’t have that. The program’s memory management is entirely up to the developer. If you make a int x;, the program actually frees the memory of this variable when it ends. But if you do something like char *p = malloc(valorAqui); that memory MUST be released in the program stream, otherwise the allocated memory will stay there until the system is rebooted.

  • @Mutley this is wrong, the memory of the heap will be released at the end of the program execution also, always. One of the functions of the operating system is precisely to control its processes. When the process is over and the memory allocated by it is obviously no longer needed it is automatically released by the OS. It would make no sense to keep it. Understand that it is the OS that controls the use of memory and not its application. The OS gives permission for your application to use portions of memory and it can take off when it wants (of course it doesn’t do it randomly).

  • So, in this case that I talked about, was the OS associating unbound allocated memory to anything? Or would it release it if necessary?

  • 2

    It wasn’t, this 80% was related to other things. When the application closes, the memory is released immediately. At most what may have happened is the application has not been closed and you didn’t notice. It is impossible for memory to be allocated to anything.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.