Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an allocator that uses alloca and is otherwise C++ STL compliant?

I have two questions:

1) Is it possible to implement an allocator that uses alloca to allocate memory on the stack and is otherwise C++ STL compliant?

If there is code out there, you can make me happy by simply pointing me to the URL. :-) If there is no code out there, perhaps you can sketch the functions allocate and deallocate?

2) If the answer to the above question is 'yes', I'd like to understand how it is possible to allocate memory on the stack for class members. As an example, consider an

std::vector<int, AllocaAllocator<int> > 

and suppose that a call of the member function 'resize' of this vector calls first 'deallocate' and then 'allocate' of the allocator.

The scope from which allocate is called is that of the member function resize. Doesn't this mean that the allocated memory is removed from the stack at the end of that function call?

Kind regards, Bjoern

like image 694
Bjoern Avatar asked Nov 02 '10 22:11

Bjoern


People also ask

What is an STL allocator?

allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec. reserve(n) of a vector vec allocates only memory for at least n elements.

Is STD vector on stack?

Stack behavior with std::vector Although std::vector can be used as a dynamic array, it can also be used as a stack. To do this, we can use 3 functions that match our key stack operations: push_back() pushes an element on the stack. back() returns the value of the top element on the stack.

Is stack a vector C++?

Stack is basically a special case of vector. Theoretically speaking vector can grow as you wish. You can remove elements at any index in a vector. However, in case of a stack you can remove elements and insert them only at its top (hence a special case of vector).


1 Answers

Bjoern, it looks like you fundamentally misunderstand how stack and alloca work. Read about them.

What you are asking is impossible because the memory allocated by alloca is "freed" when you return from the function that allocated it (and unlike Patrick said, inlining cannot change its behavior). I write "freed" because it's not actually freed, it just goes out of scope as any other stack variable. So using it afterwards causes undefined behavior.

Suppose you allocate a chunk of memory in YourAllocator::allocate which is called from d.push_back():

deque<int, AllocaAllocator> d;
d.push_back(42); // calls alloca
printf("Hello\n");
printf("%d\n", d[0]);

The memory allocated by alloca may be overwritten by the stack-frames of push_back and printf, so the output may not be 42, it may crash, or any other thing.

like image 143
Yakov Galka Avatar answered Sep 22 '22 02:09

Yakov Galka