Will malloc implementations return free-ed memory back to the system?

The following analysis applies only to glibc (based on the ptmalloc2 algorithm). There are certain options that seem helpful to return the freed memory back to the system: mallopt() (defined in malloc.h) does provide an option to set the trim threshold value using one of the parameter option M_TRIM_THRESHOLD, this indicates the minimum amount of … Read more

malloc() vs. HeapAlloc()

Actually, malloc() (and other C runtime heap functions) are module dependant, which means that if you call malloc() in code from one module (i.e. a DLL), then you should call free() within code of the same module or you could suffer some pretty bad heap corruption (and this has been well documented). Using HeapAlloc() with … Read more

How can I get the size of an array from a pointer in C?

No, there is no way to get this information without depending strongly on the implementation details of malloc. In particular, malloc may allocate more bytes than you request (e.g. for efficiency in a particular memory architecture). It would be much better to redesign your code so that you keep track of n explicitly. The alternative … Read more

How do free and malloc work in C?

When you malloc a block, it actually allocates a bit more memory than you asked for. This extra memory is used to store information such as the size of the allocated block, and a link to the next free/used block in a chain of blocks, and sometimes some “guard data” that helps the system to … Read more

Does malloc lazily create the backing pages for an allocation on Linux (and other platforms)?

Linux does deferred page allocation, aka. ‘optimistic memory allocation’. The memory you get back from malloc is not backed by anything and when you touch it you may actually get an OOM condition (if there is no swap space for the page you request), in which case a process is unceremoniously terminated. See for example … Read more

Difference between array type and array allocated with malloc

There are several different pieces at play here. The first is the difference between declaring an array as int array[n]; and int* array = malloc(n * sizeof(int)); In the first version, you are declaring an object with automatic storage duration. This means that the array lives only as long as the function that calls it … Read more

What are the differences between (and reasons to choose) tcmalloc/jemalloc and memory pools?

It depends upon requirement of your program. If your program has more dynamic memory allocations, then you need to choose a memory allocator, from available allocators, which would generate most optimal performance out of your program. For good memory management you need to meet the following requirements at minimum: Check if your system has enough … Read more