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

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

    Sadly the truly awesome alloca() is missing from the almost awesome tcc. Gcc does have alloca().

    1. It sows the seed of its own destruction. With return as the destructor.

    2. Like malloc() it returns an invalid pointer on fail which will segfault on modern systems with a MMU (and hopefully restart those without).

    3. Unlike auto variables you can specify the size at run time.

    It works well with recursion. You can use static variables to achieve something similar to tail recursion and use just a few others pass info to each iteration.

    If you push too deep you are assured of a segfault (if you have an MMU).

    Note that malloc() offers no more as it returns NULL (which will also segfault if assigned) when the system is out of memory. I.e. all you can do is bail or just try to assign it any way.

    To use malloc() I use globals and assign them NULL. If the pointer is not NULL I free it before I use malloc().

    You can also use realloc() as general case if want copy any existing data. You need to check pointer before to work out if you are going to copy or concatenate after the realloc().

    3.2.5.2 Advantages of alloca

提交回复
热议问题