4 ms·
The more I stare at that question, the more I can't figure out if you mean the obvious or the subtle pitfalls of alloca(). Off the top of my head, some of the p
by yan 17y ago
The more I stare at that question, the more I can't figure out if you mean the obvious or the subtle pitfalls of alloca(). Off the top of my head, some of the potential "evils" I can come up with is: automatic deallocation after the function (and not the scope iirc) RETs, difficulty in passing alloca-allocated memory to other functions, being totally non-thread safe, looks foreign to other devs, classic stack-allocated buffer attacks are easier on certain systems, more pernicious effects from off-by-one errors. Did you have anything else in mind?
- tptacek 17y agoOk, alloca() is a really bad question too.
- pavlov 17y agoWhy is alloca() non-thread-safe? Each thread has its own stack.
- yan 17y agoThe way I thought about it, concurrent access to objects allocated via alloca() would probably not be explicitly protected by a lock. Threads can also be killed and spawned while other threads are accessing its stack contents. Anyway, I can think of more use cases where it's a bad idea to allocate objects on thread's stacks that you're planning to share.
- pavlov 17y agoYeah, sharing objects on the thread-local stack is definitely a bad idea. But as long as the alloca'd memory is only accessed from within the same thread, it is -- AFAIK -- safe to call alloca() simultaneously from multiple threads, the same as malloc(). I think that qualifies as thread-safety by the usual definition: i.e. the function doesn't access statics or globals. (Of course this will vary depending on the CRT. I don't think any UNIXes nowadays ship without threading support in the CRT, but Microsoft Visual C++ used to have separate thread-safe and non-thread-safe C libraries.)