-2

Why does the heap increase and then decrease after a certain level and then increase again? In linux os

When i study os, and memory structure, i found some strange address increase...

the program is simple, just recursive call for stack and heap increasing.

void recursive(int count){
long stack;
long* heap;

heap = (long*)malloc(sizeof(long)*100000000000);


        heap = (long*)malloc(sizeof(long)*100000);
        if((long*)heap >= (long*)&stack){
            printf("heap is contact with stack\n");
            exit(1);
        }


printf("%diteration \\ heap : %p || stack : %p\n",count, heap, &stack);
recursive(++count);

}

  • Could be a setup of larger chunks being used (in one direction) to serve smaller chungs (in the other direction). Please provide more of that output, in text form, directly in the question. Make sure to show at least three of the sudden changes. – Yunnosch Jun 01 '20 at 09:42
  • 1
    Memory addresses, as given by `malloc` and friends do not have to increase linearly. – mrksngl Jun 01 '20 at 09:43
  • I'm not sure what exactly you mean to prove with this code? The heap may or may not be allocated at a higher address than the stack... unless malloc gave you a null pointer in return... and that's pretty much it. So what? Also: [ASLR](https://en.wikipedia.org/wiki/Address_space_layout_randomization). – Lundin Jun 01 '20 at 10:17
  • The **behaviour** of comparison between `heap` and `&stack` is **undefined** because they do not point to the members of the **same** array. – Antti Haapala -- Слава Україні Jun 01 '20 at 10:36

1 Answers1

0

Your heap pointer does not point to the top of the heap. It points to the allocated memory chunk, which could be anywhere. The closest to what you are looking for is the break pointer, which you can find by calling sbrk(0). Note that in modern systems, you don't necessarily have a continuous heap. Here is a detailed explanation: What does the brk() system call do?

Hellmar Becker
  • 2,824
  • 12
  • 18