W
W
whoami?root root_toor2016-02-13 17:28:54
C++ / C#
whoami?root root_toor, 2016-02-13 17:28:54

How to fix Stack Overflow when recursing using std::thread and templates?

Code below:

#include <iostream>
#include <algorithm>
#include <locale>
#include <exception>

using namespace std;

double last_pos = 0x00;
int N = 0x00;

void str_cut()
{	++last_pos; // падает на == 3805
  
  if (last_pos > 64*1024) {
    return;			// exit condition
  }
  else {
    try {
      str_cut();	// Move semantics ONLY!
    }
    catch (std::exception const& e) {
      throw exception{};
      cerr << "Stack Overflow detected!" << /*e << */endl;
    }
  }

}

int main()
{
  try {
    // UTF-8 settings here
    setlocale(LC_ALL, "");
    setlocale(LC_ALL, "rus");

    std::cout.flush();
    str_cut();

    system("pause");
    return 0;

  }
  catch (...) {
    // stack overflow exception handling
    throw exception{};
    cerr << "Stack Overflow detected!" << /*e << */endl;
  }

}

The program crashes from Stack Overflow.
I simplified everything for clarity, now you can see that the stack depth is stupidly exceeded (why exactly about 4000 calls?)
* Passing by value was fixed using move-semantics, there are no more leaks!
But, as I understand it, the recursion will have to be removed, at least like this: And related questions: 1) Is it enough that I set the locale to work with utf-8 at the beginning of the program? (handle Russian characters, etc.) 2) How to properly handle exceptions in this case? PS: Any advice would be welcome!
while(last_pos < 65535) str_cut();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ruchkin, 2016-02-13
@1q2w1q2w

I didn’t read the algorithm, but if I understand correctly, the smaller N, the greater the recursion depth, hence the stack overflow. It's not about the input sequence, but about local variables and function arguments. So change to cycle.
As for Access Denied and others, most likely there are other errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question