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

前端 未结 22 2459
甜味超标
甜味超标 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:20

    Most answers here largely miss the point: there's a reason why using _alloca() is potentially worse than merely storing large objects in the stack.

    The main difference between automatic storage and _alloca() is that the latter suffers from an additional (serious) problem: the allocated block is not controlled by the compiler, so there's no way for the compiler to optimize or recycle it.

    Compare:

    while (condition) {
        char buffer[0x100]; // Chill.
        /* ... */
    }
    

    with:

    while (condition) {
        char* buffer = _alloca(0x100); // Bad!
        /* ... */
    }
    

    The problem with the latter should be obvious.

提交回复
热议问题