Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened with the relocating allocator?

Tags:

c

gnu

glibc

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?

like image 474
Mabus Avatar asked Oct 09 '15 09:10

Mabus


People also ask

What is the allocator used for?

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.

What are allocators in STL?

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).

What is the default allocator template allocator?

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.


1 Answers

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.

like image 151
Employed Russian Avatar answered Oct 12 '22 10:10

Employed Russian