UPDATE: I solved it, just increased the stack size to 0x40000000, and now my code runs perfectly. (Earlier, I thought the stack size would be sufficient because I was getting a different error before (SIGSEV), and I did not think SIGBUS was also due to stack size)
I am a beginner in C++ and I have to run my recursive code on some very large inputs.
After running, I got SIGSEV Error, and I figured out that it's probably due to low stack size.
I am using CLion and I added
set(CMAKE_EXE_LINKER_FLAGS "-Wl,-stack_size,0x20000000")
to CMakeLists.txt
Now, when I run my code, I get SIGBUS Error (interrupted by signal 10: SIGBUS).
Does anyone know why this could happen and how to fix this?
My Code:
void dfs(int x, int y) {
if (vis[x][y]) {
return;
}
vis[x][y] = 1;
if (!useless[x][y]) {
int cnt_ok = 0;
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (valid(nx, ny)) {
cnt_ok += !useless[nx][ny];
}
}
useless[x][y] = cnt_ok < 2;
}
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (valid(nx, ny)) {
dfs(nx, ny);
}
}
}
This is a DFS on 2-D Grid and function valid()
checks for whether the coordinates are valid or not.
dx[4] = {-1, 1, 0, 0}
dy[4] = {0, 0, 1, -1}
The dimensions of vis
and useless
vectors are just the dimensions of the grid.
When I run with debugger in CLion:
(Line 62 is where the void dfs(int x, int y)
is written. Line 86 is where dfs(nx, ny)
is written.)
Also, if it's relevant - the file is so large that my computer becomes very slow and laggy when my code is running.
I also ran this code on smaller inputs and the code works perfectly fine.
Surprisingly, if a comment out the if (!useless[x][y])
the code runs fine even on large inputs and exits normally.
(Please focus on the code itself, I am beginner in c++, and I just implement pseudo-code given in books, so my code may not align with best practices.)
Thanks!