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

前端 未结 2 1409
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 05:38

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 the

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 06:19

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

提交回复
热议问题