Date: Tue, 6 Feb 1996 07:21:30 +0200 (IST) From: Eli Zaretskii To: John Beale Cc: djgpp AT delorie DOT com Subject: Re: malloc/free ends up fragmenting dynamic memory? On 5 Feb 1996, John Beale wrote: > I am guessing that the many malloc/free operations fragments the memory > store analgous to hard disk filesystem fragmentation with many saves and > deletes, such that a contiguous memory segment for a large malloc() can no > longer be found. Is there a malloc_unfragment() command or equivalent? How > do other people handle this problem? This is a problem with many implementations of `malloc', the one from DJGPP library included. The usual method of solving such problems in programs that allocate and free many small arrays, is to allocate a large buffer of memory and use parts of it as needed instead of calling `malloc' and `free'. One piece of knowledge that might help you: the DJGPP `malloc' always allocates blocks whose sizes are an integer power of 2; if you ask for 32KB, you get 64KB (because of the 4-byte overhead of `malloc' itself). So you might make your problems easier if you never get too close to sizes of the form 2^n for any integer n. Another possibility, in the case that your allocations only last as long as the function which allocated them, is to use `alloca' instead (which allocates the memory from the stack). This way, you don't have the fragmentation problem, and also are spared the need to call `free'.