c++linuxwindowsstack-overflowstack-size

С++ checking thread stack size with crashing


I have a crossplatform multithread program (Windows/Linux) that works fine on Linux and crashes on Windows. Searching in the internet gives me an idea, that this is because of stackoverflow: Linux and Windows thread stack sizes may differ. So how can I check each thread (not only the main one) stack size? Write to stack until the program crashes (need to work both on windows and linux)? And how get the size then?


Solution

  • My solution of knowing a thread stack size on both platforms is a simple testing program: create thread, write to stack recursively until the program crashes. And yes, it's 1MB on Windows and 8 MB on Linux ARM.

    #include <stdio.h>
    #include <stdlib.h>
    #include <thread>
    #include <iostream>
    
    #if __linux__
    #include <unistd.h>
    #endif
    #ifdef WINDOWS
    #include <windows.h>
    #endif
    
    void mySleep(int sleepMs)
    {
    #if __linux__
        usleep(sleepMs * 1000); 
    #endif
    #ifdef WINDOWS
        Sleep(sleepMs);
    #endif
    }
    
    int counter {0};
    
    void thread_func()
    {
        counter++;
        std::cout << "func recursive step: " << counter << std::endl;
        size_t sz = sizeof(unsigned long long);
        std::cout << "size of ulonglong: " << sz << std::endl;
        for(int i=0; i< 1000000; i++)
        {   
            unsigned long long crush_array[5000]; //1 element = 8 byte (on windows)
            for (auto &ar : crush_array)
                ar = 18446744073709551614;
            
            std::cout << "write " << sz*5000 <<"B array to stack" << std::endl;
            std::cout << "thread stack size is less then " << (float)(sz*5000*counter)/(1024*1024) << " MB"<< std::endl << std::endl;
            thread_func();
        }
    }
    
    int main(void)
    {
        std::thread thread_obj = std::thread(thread_func);
        thread_obj.detach();
        mySleep(50000);
        system("pause");
    }
    

    Result on Windows

    enter image description here

    Result on Linux ARM

    enter image description here