skip to Main Content

I can’t understand why this code prints different program breaks

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <ftw.h>
#include <stdlib.h>

int main()
{
    int max_size = 1024;
    char* ptr[max_size];

    int blockCount = 1000;
    int blockSize = 4*1024*1024;
    int from = 1;
    int to = blockCount;
    int step = 1;
    int i;

    printf("Program break: 0x%pn", sbrk(0));
    for(i = 0; i < blockCount; ++i)
    {
        ptr[i] = (char*)malloc(blockSize);
    }

    printf("Program break: 0x%pn", sbrk(0));
    for(int i = from; i < to; i += step)
    {
        free((char*)ptr[i]);
    }

    printf("Program break: 0x%pn", sbrk(0));
}

The output:

Program break: 0x0x5604211f1000
Program break: 0x0x560421212000
Program break: 0x0x560421212000

But if I prepend an #include <iostream> at the beginning of the file it prints the same program break.

The output:

Program break: 0x0x556617053000
Program break: 0x0x556617053000
Program break: 0x0x556617053000

Does it change the program break in headers ?
If so what can possibly change the program break in a header file ?
Also if compiled as a C code the last program break points to the initial. As if free returns the pages which are not used.
But in C++ case it doesn’t happen.

g++ version: 9.4.0

Compile options: -O0

OS/ABI: UNIX – System V

ABI Version: 0

Kernel version: 5.15.0-87-generic

Distro: Ubuntu 20.04.6 LTS

2

Answers


  1. Chosen as BEST ANSWER

    As @teapot418 stated

    Actually 4MB allocations are above the threshold for mmap so you could also expect those to not move the break at all.


  2. malloc library uses the data segment to store the heap where gets the memory used for dynamic allocation. The data segment can be expanded or shrunk by means of the sbrk(2) system call. This is done automatically by the malloc() library rutine when it needs more dynamic memory to use. After a malloc() you can expect the data segment to be increased size. I don’t know (and you don’t say it) why you intersperse malloc()/free() calls between the printing of the data segment. Including <iostream> will make no effect, not if you don’t use any of the functions/data defined there.

    Compiling the program with different compiler (c compier or c++ compiler —or a c/c++ compiler running in c or c++ mode) will result in very different program footprint, and everything can be different.

    Did you expect the output to be the same? why?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search