Posix_memalign / malloc allocates lower addresses after the first call for free
I am a little worried about the behavior of posix_memalign () and malloc () on my system. I have the following test code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int
main()
{
int i;
float *data;
for (i = 0; i < 5; i++) {
assert(!posix_memalign((void**) &data, 16, 100000 * sizeof(float)));
printf("data = %p\n", data);
}
free(data);
for (i = 0; i < 5; i++) {
assert(!posix_memalign((void**) &data, 16, 100000 * sizeof(float)));
printf("data = %p\n", data);
}
return 0;
}
In the first 5 allocations, posix_memalign () returns high addresses. After I call free (), it suddenly switches to low addresses:
% ./aligned data = 0x7f74f9974010 data = 0x7f74f9912010 data = 0x7f74f98b0010 data = 0x7f74f984e010 data = 0x7f74f93c4010 data = 0x929010 data = 0x98aaa0 data = 0x9ec530 data = 0xa4dfc0 data = 0xaafa50
The behavior is the same if I compile it as a C program (.c, gcc) and as a C ++ program (.C, g ++). The behavior is the same if I replace posix_memalign () with malloc ().
Any idea what's going on? Thank!
I am using Linux 3.2.0 / x86_64 (Ubuntu) and gcc 4.6.3.
source to share
This behavior is completely correct, and your code should not depend on what memory is allocated in any particular template.
It boils down to the details of the internal implementation of the distribution functions, but one possible explanation:
- The function
free
checks how much memory has been allocated to a process, and how much of it is actually being used, in order to decide if any memory should be released (for use by other processes). - This analysis
free
modifies some of the internal state variables used by the allocator, even if the memory is not freed. - As a result, future calls to distribution functions behave differently than they would if they were
free
not called.
source to share