Why is the use of alloca() not considered good practice?

前端 未结 22 2463
甜味超标
甜味超标 2020-11-22 03:00

alloca() allocates memory on the stack rather than on the heap, as in the case of malloc(). So, when I return from the routine the memory is freed.

22条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 03:46

    alloca () is nice and efficient... but it is also deeply broken.

    • broken scope behavior (function scope instead of block scope)
    • use inconsistant with malloc (alloca()-ted pointer shouldn't be freed, henceforth you have to track where you pointers are coming from to free() only those you got with malloc())
    • bad behavior when you also use inlining (scope sometimes goes to the caller function depending if callee is inlined or not).
    • no stack boundary check
    • undefined behavior in case of failure (does not return NULL like malloc... and what does failure means as it does not check stack boundaries anyway...)
    • not ansi standard

    In most cases you can replace it using local variables and majorant size. If it's used for large objects, putting them on the heap is usually a safer idea.

    If you really need it C you can use VLA (no vla in C++, too bad). They are much better than alloca() regarding scope behavior and consistency. As I see it VLA are a kind of alloca() made right.

    Of course a local structure or array using a majorant of the needed space is still better, and if you don't have such majorant heap allocation using plain malloc() is probably sane. I see no sane use case where you really really need either alloca() or VLA.

提交回复
热议问题