I move the pointer to the beginning of the memory p = 0 , increment it, memorize ( noerr ) the moment at which no error occurs. Then I look for a moment when the error ( err ) appears again. It turns out that the program is in the interval [noerr; err) [noerr; err) memory. But the code crashes already at the first iteration.
Ошибка сегментирования (сделан дамп памяти)
Code:
#include <iostream> using namespace std; int main() { char *p = 0, *noerr = 0, *err = 0; while (1) { try { char c = *p; if (!noerr) { noerr = p; cout << "noerr: " << (int)noerr << endl; } } catch (...) { p++; if (noerr) { err = p; cout << "err: " << (int)err << endl; break; } } } } Why try/catch does not catch a stick? How to fix the program so that it works as I planned?
OS: Linux .
decision
main.cpp :
#include <iostream> #include <csignal> #include <cstdio> #include <cstdlib> #include <fstream> using namespace std; int main(); char *begin_ptr; void find_begin() { char *p = (char*) main; while (1) { begin_ptr = p; char c = *(--p); } } void find_end() { char *p = (char*) main; while (1) { ofstream f("end.txt"); f << (int) p; f.close(); char c = *(++p); } } void sig_handler(int signo) { ofstream f("begin.txt"); f << (int) begin_ptr; f.close(); cout << "Signal " << signo << endl; cout << "begin_ptr: " << (int) begin_ptr << endl; cout << "dist from begin to main: " << ((char*)main - begin_ptr) << endl; find_end(); exit(0); } void HandlerRun () { printf("Sig Handle Initialized!\n"); signal(SIGSEGV, sig_handler); signal(SIGSTOP, sig_handler); signal(SIGTERM, sig_handler); // signal(SIGKILL, sig_handler); signal(SIGABRT, sig_handler); signal(SIGINT , sig_handler); } int main() { HandlerRun(); ofstream f("main.txt"); f << (int) main; f.close(); cout << "main: " << (int) main << endl; find_begin(); } main.sh :
./main > /dev/null beg=$(cat begin.txt) end=$(cat end.txt) echo begin: $beg echo end: $end echo end - begin: $(echo $end - $beg | bc) Example output:
begin: 134512640 end: 134529023 end - begin: 16383
void sig_handler(int signo) { printf("G with %d signals",signo); exit(0); } void HandlerRun () { printf("Sig Handle Initialized!"); signal(SIGSEGV, sig_handler); signal(SIGSTOP, sig_handler); signal(SIGTERM, sig_handler); signal(SIGKILL, sig_handler); signal(SIGABRT, sig_handler); signal(SIGINT , sig_handler); }void sig_handler(int signo) { printf("G with %d signals",signo); exit(0); } void HandlerRun () { printf("Sig Handle Initialized!"); signal(SIGSEGV, sig_handler); signal(SIGSTOP, sig_handler); signal(SIGTERM, sig_handler); signal(SIGKILL, sig_handler); signal(SIGABRT, sig_handler); signal(SIGINT , sig_handler); }- pavel