Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

How widely used is alloca in the real world? Should I teach my students to use alloca when it makes sense? Or should I teach them never to use it? Coming from a C++ RAII background, the idea of not having to call free manually sounds promising, especially in functions with multiple exit points.

share|improve this question
Related: stackoverflow.com/questions/1018853/… – delnan Oct 25 '11 at 13:51
5  
Why not teach them C99 VLAs ? – cnicutar Oct 25 '11 at 13:52
@cnicutar alloca() is implementation-dependent but at least many implementations return NULL on failure. C99 VLAs have no way to indicate failure. – Complicated see bio Oct 25 '11 at 13:53
2  
@sbi: For SO this is an open-ended question that doesn't really fit the format of what the closers think SO posts ought to be. It is too subjective, there is no clear cut answer, merely opinion. Which is fine but not for SO. Notice also that out of respect for the OP's rep no one is down voting, we're just closing this question as off topic. – Paul Sasik Oct 25 '11 at 13:54
@PascalCuoq You shouldn't be allocating a lot with alloca / VLAs anyway. If unsure what "a lot" is in the current context, use malloc. – cnicutar Oct 25 '11 at 13:56
show 4 more comments

migrated from stackoverflow.com Oct 25 '11 at 13:58

8 Answers

If you are holding a course in general C programming, you shouldn't teach them a thing that is not in the standard. Beginner programmers needlessly writing non-standard and/or non-portable code because they were taught that way, has been a huge problem for the software industry during the past 20-30 years or so. The cost for not teaching them the standard and nothing but the standard is likely astronomic.

If you are holding a more advanced course in algorithms or application programming, it might be good to mention it. On the other hand, I have programmed everything from hard realtime embedded apps to Windows application fluff for 15 years without ever using that function.

share|improve this answer

I can see two things happening:

  1. The students understand the impact of alloca, read about the differences between stack and heap, and use alloca carefully. (unlikely)

  2. The students think "wow, this is like malloc without worrying about the free," use it excessively, get stack overflow, and have no idea what's up.

I think it's much better if you describe alloca, then run this code:

#include <malloc.h>

int OverflowMyStack(int start) {
    if (start == 0)
        return 0;

    char * p = (char *)_alloca(4096);
    *p = '0';
    return OverflowMyStack(start - 1);
}

int main () {
    return OverflowMyStack(512);
} 

Source: http://www.strchr.com/alloca

show them the dangers, and then tell them not to use it. They'll still learn about stack vs. heap, see the perils in action, and can move on with standard stuff.

share|improve this answer
I think most students still fall into the second category even after showing them the example code. – rightfold Oct 31 '11 at 21:33
@WTP - Probably, but that's why you tell them not to use it even after showing them what can happen. – BlackJack Oct 31 '11 at 23:02
Why does that code use _alloca rather than alloca? And why does it cast the result? – Keith Thompson Nov 1 '11 at 2:06

The answer to this question should be based on what your objectives are in the first place.

Do you want to teach someone who already knows how to program how to write C and work with existing C code in the wild? If so, tell about alloca and anything else you want.

On the other hand, if you are teaching an introductory course that only is using C by coincidence (and because C is a very small language and so on) you should focus on the important parts (writing modular programs, subroutines, collections, ...). From a student's perspective, alloca is a bir redundant since malloc is enough in most cases and from a good-code perspective you are better off explicitely mentioning how manual memory management is annoying and how other languages deal with this problem After all, there are more things to memory management then alloca or RAII so you really shouldn't restrict yourself to these and as you mentioned already, its much easier to understand the purpose of alloca if you compare it to other "more standard" ways to do things in other languages (or C99...)

share|improve this answer

We do embedded systems in pure C. I have very carefully used alloca() for small tables where I don't know the size at compile time. (Otherwise, just declare an array.)

Our stacks are 2-4k so we have to be very careful using alloca(). But it is quite useful at times.

For example, a protocol decode function. Our protocol uses a Type-Length-Data format. Read sizeof(header) from USB, decode, find the size of the next header structure. alloca() that size. Must make sure to sanity check sizes every step of the way or stack overflow!

share|improve this answer
Personally I wouldn't use it even in this scenario. Advantage of alloca - no need to state maximum length - quickly turns into unsafe code compared to fixed length array designed to hold longest message. Fixed array makes worst case stack usage explicit and helps static analyzer to do its job. If you receive longer message than fixed limit you can act still on it. – MaR Oct 25 '11 at 15:56
The static analyzer is a good point. – David Poole Oct 25 '11 at 16:30

I mostly don't code in C or C++ these days, but learning about alloca (and about its pitfalls) increased my understanding of how those languages that in turn improved my understanding of how heaps and stacks work. Knowledge of those certainly comes up around here from time to time.

What's the worse that could happen, they learn something? ;)

share|improve this answer
It "increased your understanding of how those languages"... what? – sbi Oct 25 '11 at 14:04
+1! Any serious programmer should know how the underlying machine works (stack vs heap, etc). – David Poole Oct 25 '11 at 14:08
The stack is a C invention. The computer can work really well without it so C is not that good of a model for the base machine – missingno Oct 25 '11 at 14:23
@missingno Uh, what? Why do x86 processors have stack frame and stack pointer registers? Why does the call operation use parameters that have been pushed onto the stack? Where does the call operation put its return address? What are the push and pop operations for? All of these things are assembly code instructions, not C. – AlexWebr Nov 25 '11 at 9:44
@AlexWebr: I was trying to refer to the function == stack frame concept that is so ingrained in C. If you program in assembly language you don't need to use "The Stack" if you don't want to. – missingno Nov 25 '11 at 12:22

No.

The only reason a C programmer should even be aware of alloca's existence is to understand and fix legacy code that's using it.

Any use of alloca is either

  1. Useless, i.e. it could trivially be replaced by fixed-size variables of automatic storage duration, OR
  2. A dangerous stack overflow waiting to happen.

Aside from a few thought experiments for which I have never found any real-world examples, there is no usage case for alloca (or VLA's) that's not either useless or vulnerable (one of the above 2 cases).

share|improve this answer
1  
Of course, absolutely nobody could ever possibly use it responsibly. No, never. – DeadMG Oct 25 '11 at 17:57
The only "responsible" use of alloc is 100% equivalent to fixed-size automatic arrays, and less portable. – R.. Oct 25 '11 at 19:52
I guess, then, that nobody could ever want to allocate some dynamic amount, say, a few kilobytes which would never overflow. Or call some OS API function which will tell them how much is available. Or just increase the stack size to a lot. – DeadMG Oct 25 '11 at 22:50
If it's a few KB and you're confident you have a few KB, you can just use T foo[5000]; or whatever. – R.. Oct 26 '11 at 1:14
Only if T has a trivial default constructor. If I was performance-needy, even simple zeroing of memory might cost me. But other types can have even more complex default-construction logic. If I wanted to, for example, dynamically create an array of std::mutex, I might invoke a kernel call and context switch for five thousand mutexes. Not cheap. Not to mention the additional cache cost of placing local variables after the array. – DeadMG Oct 26 '11 at 1:20
show 2 more comments

My opinion is do not encourage using it unless you are teaching low level compiler principles used to allocate stack space for local variables. Teach it in that context.

share|improve this answer

It exists for a purpose, and its effect cannot be reproduced except by VLA. I think it would be a good idea to make them aware of it.

Besides, why are you teaching them C if you would want to hide these details?

share|improve this answer
3  
Because alloca isn't a standard C function. Teach them the C language, not 3rd party libraries. – Lundin Oct 25 '11 at 14:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.