I was reading old glibc documentation here when I saw three strange functions that I had never seen before (r_alloc, r_alloc_free and r_re_alloc). They implemented an allocator that realocates memory for defragmentation purposes, I think, but I can't find more info anywhere else.
Can you tell me more about that functions? Are they still in Glibc? If not, why they were removed?
This is the allocator that all standard containers will use if their last (and optional) template parameter is not specified, and is the only predefined allocator in the standard library. Other allocators may be defined.
Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers. This section describes the default allocator template allocator (lowercase).
This section describes the default allocator template allocator (lowercase). This is the allocator that all standard containers will use if their last (and optional) template parameter is not specified, and is the only predefined allocator in the standard library. Other allocators may be defined.
Can you tell me more about that functions?
What do you want to know about them? They are pretty clearly described in the manual in which you've found them.
They are somewhat similar to Win32 LocalAlloc
and LocalLock
-- you get a handle to memory object, but to get the usable address of that object requires an extra step. These are generally a bad idea, except on extremely memory constrained systems.
Are they still in Glibc?
No.
If not, why they were removed?
Because they are generally a bad idea, and breed to hard-to-find bugs.
Update:
What kind of bugs are possible by using something like that?
Here is an example:
const char *my_strcat(const char *a, const char *b)
{
const size_t len_a = strlen(a);
const size_t len_b = strlen(b);
char *handle;
if (r_alloc((void**)&handle, len_a + len_b + 1) == NULL) return NULL;
memcpy(handle, a, len_a);
memcpy(handle + len_a, b, len_b + 1);
return handle;
}
// There are memory leaks here. Ignore them for now.
int main()
{
const char *result = my_strcat("abc", my_strcat("def", "ghi"));
return strcmp(result, "abcdefghi");
}
Can you spot the bug?
The program will sometimes succeed, sometimes fail with non-zero exit code, and sometimes crash with SIGSEGV
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With