5 ms·
I disagree, I think this actually a pretty good question, if asked properly. If you expect the right answer right away, then yes, it's a useless piece of trivia
by coffeemug 17y ago
I disagree, I think this actually a pretty good question, if asked properly. If you expect the right answer right away, then yes, it's a useless piece of trivia. But if you ask people to think it through, you might uncover a surprising lack of understanding of what's going on under the hood (stack vs. heap, etc.) If your goal is to have people think it through and explain their thinking along the way, it's not a bad question at all (assuming your goal is to hire someone who knows C++ well - whether it's a good goal is a whole different question).
- tptacek 17y agoEven with heap-allocated objects there are lots of cases where you can't safely "delete this", which is what makes it a worst-practice. If you just want to know whether the candidate knows what the heap is, ask them to explain why alloca() is evil.
- yan 17y agoThe 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.)