Quote:
Originally Posted by golden_boy615
how can I free allocated memory with malloc immediately
|
To free more memory immediately, you could write your own version of malloc. Even then, without significant waste during allocation, you couldn't return each chunk immediately when freed. Malloc must get and release whole 4096 byte pages of memory. But your program gets and releases chunks that are not page aligned.
Why do you want to free allocated memory immediately? In most programs there would be very little benefit (and large cost) to doing so.
You might have a program that allocates a
lot of memory early, then finishes with that memory, then continues to run for a long time using little memory. That produces an unnecessarily load on the system memory until Linux figures out the stale pages should be swapped out, then there is the cost of that swapping, then additional cost when the process shuts down. That still doesn't add up to enough to justify a big programming effort unless there is extra reason to really care about the system impact of that program.
In the unlikely case that it is worth programming effort, you could use a pool allocation that you manage yourself for the large memory use that will be returned early. If you get a big enough chunk from malloc, then malloc will usually allocate it in a different way and release it immediately when your program frees it. You may need to look at malloc source code (and/or experiment) to see what that size is for your version of malloc. Alternately, you can get any page aligned multiple of the page size directly from the kernel and return it directly to the kernel bypassing malloc.