0

I was just wondering if there was a way to free all memory at once in a program instead of doing a ton of free() functions, such as the following;

free(somevariable);

Its not really a problem, but just seems sort of excessive to do that for every variable if a program contains many of them, if there was sort of a catch-all to free all memory at the end, or a way to supply more than one variable at a time to free(), such as the following again, I would find that immensely helpful, thanks!

free(var1,var2,var3)
lacrosse1991
  • 2,972
  • 7
  • 38
  • 47
  • 8
    What would be the point of "freeing all memory"? You can achieve this by calling `exit(0)`; but then there's also no more program. – Kerrek SB May 19 '12 at 23:52
  • 1
    The correct way to write C with arbitrary allocations and multiple is to use `goto` judiciously, as shown in [this answer](http://stackoverflow.com/a/10464368/596781); otherwise stick to short, manageable functions. – Kerrek SB May 19 '12 at 23:54
  • If what you want to do is possible, then why not free an array of pointers to pointers once and for all? Instead, you have to free them one by one... though, in that case at least you can iterate through matrix indices – PALEN May 19 '12 at 23:55
  • ok thanks, will stick to using the individual free()'s for now – lacrosse1991 May 20 '12 at 00:45
  • also sorry if this was sort of a dumb question, new to C so still getting a grip on things – lacrosse1991 May 20 '12 at 01:19

5 Answers5

5

You need a call to free() for each call to malloc().

That doesn't necessarily mean that each malloc() call in your source code needs to have a corresponding free() call; it's the calls at run time that have to match, not the calls in your source code. But usually the source calls will match.

I should also note that free()ing all malloc()ed memory isn't absolutely required. When your program terminates, all allocated memory will be returned to the operating system. (The C standard doesn't guarantee this, but any OS you're likely to be using will do this.) But cleaning up after yourself is a good habit; for example, a program can become part of a larger program.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
1

Here:

#include <stdlib.h>
#include <stdarg.h>

void vfree(int count, ...) {
        va_list ap;
        int i;

        va_start(ap, count);

        for (i=0; i<count; i++) {
                void *ptr;
                ptr = va_arg(ap, void *);
                printf("arg %d = %p\n", i, ptr);
                free(ptr);
        }

        va_end(ap);
}

Call it like this:

vfree(3, ptr1, ptr2, ptr3);

That is, give it a count of pointers, and then the list of pointers, and it will call free on all of them.

NB: This is a terrible idea and a terrible implementation and you shouldn't use it.

larsks
  • 277,717
  • 41
  • 399
  • 399
1

If your compiler supports __VA_ARGS__ (gcc does and the latest Visual C++ should), then you could do something like this:

#include <stdio.h>
#include <stdlib.h>

#define FREE(...) \
  { \
    void* pointers[] = { __VA_ARGS__ }; \
    size_t i; \
    for (i = 0; i < sizeof(pointers) / sizeof(pointers[0]); i++) \
      printf("freeing %p\n", pointers[i]); \
      free(pointers[i]); \
  }

int main(void)
{
  void *p1 = malloc(1), *p2 = malloc(2), *p3 = malloc(3);
  printf("p1=%p, p2=%p, p3=%p\n", p1, p2, p3);
  FREE(p1, p2, p3);
  return 0;
}

Output:

p1=005E17C0, p2=005E17E0, p3=005E17F0
freeing 005E17C0
freeing 005E17E0
freeing 005E17F0
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • +1 for an original answer. But I think this doesn't avoid the main problem behind the question, having to keep track of all the allocated pointers. The syntax of using that information is probably secondary. – Jens Gustedt May 20 '12 at 07:04
  • @JensGustedt: In C and assembly the programmer must be aware of all the details and create tools to make the code more readable and more robust. The accepted answer shows a solution that makes another step in that direction. – Alexey Frunze May 20 '12 at 07:29
1

You should stop and think about what you're asking for for a second. It doesn't make sense. If your only goal is to call "freeall" just before exiting, it's useless; terminating the program will already cause its entire memory space (including all allocations made by malloc) to cease to exist. If on the other hand you want to "freeall" at some other point before program termination, you've just violated all third-party code that might be linked into your program by deallocating its memory behind its back (how could it know your code is going to free its memory?)

With that said, there is something similar to what you want, which DOES work: talloc:

http://talloc.samba.org/talloc/doc/html/index.html

The idea of talloc is that you can make contexts of related memory allocations, and free them all together with a single call to talloc_free. It's not only very convenient, but also simplifies allocation/deallocation logic and should reduce the incidence of bugs due to incorrect deallocation (double free, leaks, etc.).

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • oh so even though so when valgrind mentions the memory leaks, its just being on the safe side, even though they are taken care of automatically when the program exits? – lacrosse1991 May 20 '12 at 04:56
  • 1
    "They" are not what's taken care of. It's the very existence of the process that's taken care of. As an analogy, imagine a filthy building you're about to have torn down. If you were going to keep using it, it would make sense to clean, but if you're about to tear it down, cleaning it first has no benefit. Now imagine it's an apartment building with people living there and not going to be town down anytime soon. You wouldn't want a "clean all" operation because you'd interfere with each tenant's stuff and their idea of what they're still using versus what's junk. – R.. GitHub STOP HELPING ICE May 20 '12 at 15:34
0

You need a smart pointer which takes care of memory management for your data structure.

Edit :- thanks to Oli , just realized its a pure C question. Smart pointers is a C++ construct.

In C you have to essentially have a free for every explicit allocation you do.

Jay D
  • 3,263
  • 4
  • 32
  • 48