lundi 17 février 2020

C++ lambda runs into a stack overflow when a large chunk of memory used on the stack, why? [duplicate]

I was playing with lambdas and I ran into a stack overflow when I allocated a large memory on the stack:

#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <thread>

int main()
{
    std::unique_ptr<std::thread> myThread;
    myThread = std::make_unique<std::thread>(
        std::thread(
            []() {

                char b[5308416]; //large chunk of memory on stack causing abort on runtime: call stack below

                while (1)
                {
                //char* b = new char[5308416]; //Its fine when I am allocating the memory on the heap, and i did not delete it to use even more memory. It took 384 cycle to abort
                    std::cout << "out" << std::endl;
                }
            }));



#pragma region exit
    int exitCode;
    std::cin >> exitCode;
    return exitCode;
#pragma endregion exit
}

Callstack in case of stack overflow:

>   sandbox_winapi.exe!_chkstk() Line 99    Unknown
    sandbox_winapi.exe!std::_Invoker_functor::_Call<void <lambda>(void)>(main::__l2::void <lambda>(void) && _Obj) Line 1579 C++
    sandbox_winapi.exe!std::invoke<void <lambda>(void)>(main::__l2::void <lambda>(void) && _Obj) Line 1579  C++
    sandbox_winapi.exe!std::thread::_Invoke<std::tuple<void <lambda>(void)>,0>(void * _RawVals) Line 43 C++
    ucrtbased.dll!thread_start<unsigned int (__stdcall*)(void *),1>(void * const parameter) Line 97 C++
    kernel32.dll!@BaseThreadInitThunk@12() Unknown
    ntdll.dll!__RtlUserThreadStart()    Unknown
    ntdll.dll!__RtlUserThreadStart@8() Unknown

Callstack in case of large memory allocation on heap:

KernelBase.dll!_TerminateProcessOnMemoryExhaustion@4() Unknown
CoreMessaging.dll!Cn::Process::NotifyOutOfMemory(unsigned int)  Unknown
CoreMessaging.dll!Microsoft::CoreUI::Buffering::LargeBlockPool::Initialize(bool)    Unknown
CoreMessaging.dll!Microsoft::CoreUI::Dispatch::ThreadContext::ModuleInitialize(bool)    Unknown
...

I am curious what is happening behind this? Is there a restriction for lambdas or it is something else causing this issue? What is the limit of this? I suppose I am missing some significant knowledge about heap and stack? Can somebody point me to the right direction to understand this behavior?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire