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

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

    One of the most memorable bugs I had was to do with an inline function that used alloca. It manifested itself as a stack overflow (because it allocates on the stack) at random points of the program's execution.

    In the header file:

    void DoSomething() {
       wchar_t* pStr = alloca(100);
       //......
    }
    

    In the implementation file:

    void Process() {
       for (i = 0; i < 1000000; i++) {
         DoSomething();
       }
    }
    

    So what happened was the compiler inlined DoSomething function and all the stack allocations were happening inside Process() function and thus blowing the stack up. In my defence (and I wasn't the one who found the issue; I had to go and cry to one of the senior developers when I couldn't fix it), it wasn't straight alloca, it was one of ATL string conversion macros.

    So the lesson is - do not use alloca in functions that you think might be inlined.

提交回复
热议问题