Problem:
We are writing programs often found that the program uses more memory than we apply, in order to optimize the memory footprint of the program, the brain to optimize the memory footprint, but found that their code can not be optimized, how to do? Now we put our focus on the malloc, after all, the memory we have applied to the system is done through it, do not understand him, can not completely optimize the memory footprint.
Here's a little example.
g++-o malloc_addr_vec mallc_addr_vec.cpp compiled
#include <iostream>
using namespace std;
int main (int argc, char *argv[])
{
int malloc_size = atoi (argv[1]);
char * MALLOC_CHAR;
for (size_t i = 0; i < 1024*1024; ++i) {
Malloc_char = new Char[malloc_size];
while (1) {}//View memory occupancy return 0 at this time
;
}
This article's test environment is the Linux 64Bit, uses the g++ to compile as the executable file, starts with the different startup parameter, uses the top command to view the memory which the program occupies, here we mainly see RES index
RES--Resident size (KB)
The non-swapped physical memory a task has used.
Test Case:
1. Every new 1 Byte do 1024*1024 times
./malloc_addr_vec 1
Memory footprint after starting the program
Memory consumption 32MB
2. Each time new Byte do 1024*1024
./malloc_addr_vec 24
Memory footprint after starting the program
Memory consumption 32MB
3. Each time new Byte do 1024*1024
./malloc_addr_vec 25
Memory footprint after starting the program
Memory consumption 48MB
Why do we use the same memory each time the new 1Byte and every new 24Byte system consumes? , why is the memory of new 25Byte and each new 24Byte completely different?
I wonder if you have ever paid attention to this problem while writing a program. I met one time, spit a slot: What the fuck malloc.