Tutorial :Force garbage collection/compaction with malloc()



Question:

I have a C++ program that benchmarks various algorithms on input arrays of different length. It looks more or less like this:

# (1)  for k in range(4..20):    # (2)    input = generate 2**k random points    for variant in variants:      benchmark the following call      run variant on input array    # (3)  

Is it possible to reset the whole heap management at (2) to the state it had at (1)? All memory allocated on the heap that was allocated during the program is guaranteed to be freed at (3).

I am using g++ 4.3 on Linux.

Edit: I understand that there is no real garbage collection in C/C++. I want to force the memory allocation to join adjacent empty chunks of memory it has in its free list at (2).


Solution:1

If you want the test runs to start in the same heap states, you can run them in their own processes created by fork().


Solution:2

I think there's a simple solution to your problem - you could move the outside loop outside of your application and into a shell script or another application and pass the (k) (and any other) parameters through the command line to the benchmarked app - this way you'll be sure all executions had similar starting conditions.


Solution:3

There is no way of doing this using Standard C++ short of implementing your own versions of new & delete with their own heap management. An alternative would not be to use arrays but use std::vectors instead - you can then use a custom allocator to do the heap management.


Solution:4

What do you mean? There is no garbage collection in C, and certainly no compaction.

To "reset the state of the heap", you have to call free() for every malloc() call. And as I understand your code, you do that already.

Compaction is pretty much impossible. Unlike higher-level languages like Java or C#, you can not change the address of an object, because any pointers to it would be invalidated.


Solution:5

There's no automatic way, you have to manually delete whatever is on the heap to get back to the state of (1).


Solution:6

Their are a few pieces of garbage collection code out their. Look at perl/python/lua/ruby/mono/parrot/boehm/pike/slate/self/io etc etc. Also look at alloca() and dynamic arrays. Also consider using structs to implement your own destructor or using gcc attributes to call free when a function leaves scope.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »