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

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

    Here's why:

    char x;
    char *y=malloc(1);
    char *z=alloca(&x-y);
    *z = 1;
    

    Not that anyone would write this code, but the size argument you're passing to alloca almost certainly comes from some sort of input, which could maliciously aim to get your program to alloca something huge like that. After all, if the size isn't based on input or doesn't have the possibility to be large, why didn't you just declare a small, fixed-size local buffer?

    Virtually all code using alloca and/or C99 vlas has serious bugs which will lead to crashes (if you're lucky) or privilege compromise (if you're not so lucky).

提交回复
热议问题