Parsing the operating system's memory allocation (malloc) alignment policy

Source: Internet
Author: User


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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.