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

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

    alloca() is very useful if you can't use a standard local variable because its size would need to be determined at runtime and you can absolutely guarantee that the pointer you get from alloca() will NEVER be used after this function returns.

    You can be fairly safe if you

    • do not return the pointer, or anything that contains it.
    • do not store the pointer in any structure allocated on the heap
    • do not let any other thread use the pointer

    The real danger comes from the chance that someone else will violate these conditions sometime later. With that in mind it's great for passing buffers to functions that format text into them :)

提交回复
热议问题