C++ How to allocate memory dynamically on stack?

后端 未结 7 1064
南旧
南旧 2020-12-04 11:07

Is there a way to allocate memory on stack instead of heap? I can\'t find a good book on this, anyone here got an idea?

7条回答
  •  长情又很酷
    2020-12-04 11:47

    Article discussing about dynamic memory allocation

    We can allocate variable length space dynamically on stack memory by using function _alloca. This function allocates memory from the program stack. It simply takes number of bytes to be allocated and return void* to the allocated space just as malloc call. This allocated memory will be freed automatically on function exit.

    So it need not to be freed explicitly. One has to keep in mind about allocation size here, as stack overflow exception may occur. Stack overflow exception handling can be used for such calls. In case of stack overflow exception one can use _resetstkoflw() to restore it back.

    So our new code with _alloca would be :

    int NewFunctionA()
    {
       char* pszLineBuffer = (char*) _alloca(1024*sizeof(char));
        …..
      // Program logic
         ….
      //no need to free szLineBuffer
      return 1;
    }
    

提交回复
热议问题