0

I have just upgraded to MacOS Monterey and I am seeing some unusual behaviour in terms of addresses returned when allocating memory on the heap (malloc/new). It seems that if you ask for more than 256 bytes you get an address just above PAGE_ZERO (0x100000000), but if you ask for 256 bytes or less you get an address above 0x600000000000.

I know that the c library is free to return whatever address it likes when allocating on the heap and this shouldn't matter to your code. But my code relies on the heap addresses being in the same area of memory. I know this is bad programming, but there are reasons for it.

Is there any way of making Monterey allocate memory in the same area of memory (aside from always allocating more than 256 bytes)? Thank you for any ideas.

Example code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    size_t i,count = 2;
    for (i = 0; i < 16; i++)
    {
        void *ptr = malloc(count);
        printf("malloc(%d) returned %p\n",count,ptr);
        count *= 2;
    }
    for (count = 250; count < 260; count++)
    {
        void *ptr = malloc(count);
        printf("malloc(%d) returned %p\n",count,ptr);
    }
    return 0;
}
Dim St Thomas
  • 103
  • 1
  • 7
  • 1
    I think you are pretty much in unsupported territory. Maybe allocate huge blocks and do your own memory management inside them? – r_ahlskog Oct 29 '21 at 07:25
  • This may (or may not) be a result of binning i.e. allocating memory chunks of certain specific sizes from respective bins which are reserved for this. I've read some years ago about this. It's a strategy against fragmentation of heap. This is something which is obviously used for smaller memory sizes as the allocation of objects for class instances (which always have a specific size) is something which probably happens very often. – Scheff's Cat Oct 29 '21 at 08:01
  • 3
    Using a simple memory pool should probably serve your needs. However, I think you should state the actual reasons why this is a problem. I suspect you're doing something highly questionable (_e.g._ undefined / unspecified behavior per C++ spec) with these pointers. It should not matter what address they hold. – paddy Oct 29 '21 at 08:04
  • Thank you for the replies. Sounds like there is no way I can change the behaviour, so will probably go with always allocating more than 256 bytes. And yes, I am doing something highly questionable that I would never do if writing code from scratch. – Dim St Thomas Oct 29 '21 at 08:33
  • 1
    In that case, you probably should explain why you need that. Maybe there is still a way to fix that _"highly questionable"_ questionable thing you do, or to at least give you suggestions on how to deal with that. – t.niese Oct 29 '21 at 08:36
  • We're here to help you not shoot yourself in the foot. But if you don't say what you're doing and why, then we really can't prevent disaster. – paddy Oct 29 '21 at 08:57

0 Answers0