Cpp - EXC_BAD_ACCESS in recursion [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Ive written a recursive function which uses std::vector for temporary data containers. The problem is that the code throws errors of EXC_BAD_ACCESS after certain recursive iterations, which dont seem to be associated with the code since the exception travels around.
I can produce an exception if i put anything at the place of the code printf("This is funny ... not"), any code before that seems to be executing okay.
I suspect that my system has run out of memory but from the activity monitor I can see that ive used 6.5 / 8GB RAM so this cannot be the case?
What may be the case of this EXC_BAD_ACCESS exception?
void Terrain::CarvePath(int index){
float endElevation = 0.0f;
int actualRowSize = 25 + 1;
int upperRow = index - actualRowSize;
int bottomRow = index + actualRowSize;
if(bottomRow + 1 > 25 * 25 || upperRow - 1 < 0){
return;
}
std::vector<int> surroundingIndices;
// Throws EXC_BAD_ACCESS. If removed throws EXC_BAD_ACCESS
// on the next line ( surroundingIndices.push_back() )
printf("This is funny ... not");
surroundingIndices.push_back(upperRow - 1);
surroundingIndices.push_back(upperRow);
surroundingIndices.push_back(upperRow + 1);
surroundingIndices.push_back(index - 1);
surroundingIndices.push_back(index + 1);
surroundingIndices.push_back(bottomRow - 1);
surroundingIndices.push_back(bottomRow);
surroundingIndices.push_back(bottomRow + 1);
if(lastVertex){
std::remove(std::begin(surroundingIndices),
std::end(surroundingIndices), lastVertex);
}
std::vector<float> surroundingIndicesY;
for (auto &&surroundingIndex : surroundingIndices) {
surroundingIndicesY.push_back
(vertices[surroundingIndex].position.y);
}
std::vector<float>::iterator it;
it = std::min_element(surroundingIndicesY.begin(),
surroundingIndicesY.end());
long vertexToDigIndexTemp =
std::distance(surroundingIndicesY.begin(), it);
int vertexToDigIndex = surroundingIndices[vertexToDigIndexTemp];
vertices[vertexToDigIndex].position.y -= 1.0f;
lastVertex = vertexToDigIndex;
if(vertices[index].position.y == endElevation) return;
CarvePath(vertexToDigIndex);
}

Seems to me like a typical stack overflow. Since your code is recursive, you might end up with a lot of return addresses on the stack, which can lead to your stack running out of space. Converting your code to a non-recursive version could solve the problem.

Related

Why am I getting segmentation fault error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am writing a C ++ program that needs to convert numbers from decimal to binary. Here is my code:
int* convertToBinary(int i, unsigned int n) {
int ans[10000];
if (n / 2 != 0) {
convertToBinary(i + 1, n / 2);
}
ans[i] = n / 2;
return ans;
}
void send_number(int num) {
for (int j = 0; j < 16; j++) {
printf("%d", convertToBinary(0, num)[j]);
}
}
In this case, the num variable takes only natural values from 0 to 65535.
The main function is send_number().
On execution I get the 'Segmentation fault (core dumped)' error. I can't figure out why this is happening.
PS: I am C++ beginner. I don't know English well and use google translator
There are 2 issues at play - scope and (related) dangling pointers.
When you define any variable inside a function - it is only valid inside that function.
convertToBinary returns a pointer that refers to invalid memory. So when you try to print it - you are using
convertToBinary(0, num)[j]
Think about what this does. You take an invalid pointer returned by the function and add an offset j to it.

Why is my C++ code giving segmentation fault(core dumped)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am getting segmentation fault(core dumped) at the time of compilation in my program. I am not able to detect the problem with the program. I am pasting my code. If anyone gets the problem then, please reply.
#include<bits/stdc++.h>
using namespace std;
typedef long double ld;
int main()
{
int a,b,c;
cin>>a>>b>>c;
ld dp[101][101][101];
for(int i=100;i>=0;i--)
{
for(int j=100;j>=0;j--)
{
for(int k=100;k>=0;k--)
{
if(i==100 || j==100 || k==100)
{
dp[i][j][k] = 0;
}
else
{
long double cnt = i+j+k;
dp[i][j][k] = 1 + (1.0*i/cnt)*dp[i+1][j][k] + (1.0*j/cnt)*dp[i][j+1][k] + (1.0*k/cnt)*dp[i][j][k+1];
}
}
}
}
cout<<dp[a][b][c];
return 0;
}
Compilation error and Segmentation fault are entirely different things. When compiler errors, you can't run the code at all. Seg-fault happens after running the code.
There are few places where the program can crash:
When i = j = k = 0, the value of cnt is also 0. Attempt to divide by 0, 1.0 * i / cnt results in crash.
If user enters anyone of the values among a,b,c as negative or more than 100, then the final cout statement will cause array out of bound and is again a good candidate for crash.

I have no idea why only one code has SIGSEGV between two code (looks same) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
First time, I coded like this (I was making a trie) and when I called add("911"); I got a segmentation fault at there when *str == '1'
struct Node {
int check, check2;
Node* chd[10];
Node() : check(0), check2(0), chd{0, } {}
~Node() {
for (int i = 0; i < 10; i++)
if (chd[i])
delete chd[i];
}
int add(char* str) {
if (!str[0])
return 0;
if (chd[*str-'0'] == 0) // here I got SIGSEGV
chd[*str-'0'] = new Node();
...
return chd[*str-'0']->add(++str);
}
}
then I fixed that part like this
int i = *str-'0';
if (chd[i] == 0)
chd[i] = new Node();
there was no error.
What's the difference? What made the first code make error?
(I was solving ACM-ICPC > Regionals > Europe > Northwestern European Regional Contest > Nordic Collegiate Programming Contest > NCPC 2007 A)
return chd[*str-'0']->add(++str);
contains undefined behavoir as you are modifying and using str unsequenced.
Your 'fix' has the classic behavoir of moving something around enough that the undefined behavoir is hidden. Remeber that Undefined Behavoir is undefined. It doens't have to crash. It doesn't even have to make sense. And most scarily it can do what you expect... for the time being at least.
A simple change is:
return chd[*str-'0']->add(str+1);
This line has undefined behaviour
return chd[*str-'0']->add(++str);
because the modification and the use of str are unsequenced.
The quick fix is (don't say ++ when you mean + 1):
return chd[*str-'0']->add(str + 1);
but you can also avoid the problem by computing the relevant index just once (it sounds like this is how you fixed the problem, and it's the better solution):
int add(char* str) {
if (!str[0])
return 0;
char c = str[0] - '0';
if (chd[c] == 0)
chd[c] = new Node();
...
return chd[c]->add(str + 1); // And ++str would also work...

Concurrent write to std::vector to different indices causes crash? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a big vector and i want to update some data in that vector (no insert/delete, but rather replacing an element with another on a specified index).
I was thinking that this is pretty clever to do the work on 2 or more different threads, therefore improving the speed. And since no synchronization is really necessary in this case, due to different indices this should be really fast.
Unfortunately my code crashes, either by stating: EXC_BAD_ACCESS, or "pointer being freed was not allocated".
The pseudocode:
// I have an entries_ vector with data of type DataT
std::vector<std::thread> workers(NUMBER_OF_PARALLEL_CHUNKS);
unsigned long tuplesPerChunk = entries_.size() / NUMBER_OF_PARALLEL_CHUNKS;
for (int j = 0; j < NUMBER_OF_PARALLEL_CHUNKS; ++j) {
unsigned long offset = tuplesPerChunk * j;
workers.emplace_back(std::thread([&offset, &tuplesPerChunk, this](){
for (int i = 0; i < tuplesPerChunk; ++i) {
unsigned long offsetIndex = offset + i;
entries_[offsetIndex] = createNewDataForSomeParticularReason();
}
}));
}
for (auto &worker : workers) {
if (worker.joinable()) worker.join();
}
Capture offset by value, else you have dangling pointer.
Your threads live from inside the loop until the join.
offset only lives inside one loop iteration.

For loop variable going to hell for seemingly no reason? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.
The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:
void enterdata(float dpoint,int num){
autodata[num] += dpoint;
}
float autocorr(){
float autocorrelation = 0;
for(int a = 0; a<SIZEX; a++)
{
for(int b = 0; b<SIZEY; b++)
{
if(grid[a][b] == reference[a][b]){autocorrelation++;}
}
}
autocorrelation /= SIZEX*SIZEY;
autocorrelation -= 0.333333333333;
return autocorrelation;
}
for (long z = 0.0; z<MAXTIME; z++)
{
for (long k=0; k<TIMESTEP; k++)
{
grid.pairswap();
}
if (z == autostart_time)
{
grid.getreference();
signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
}
if ((z*10)%dataint == 0)
{
if (signal == 1) {
//!!! this is the important segment!!!
cout << z << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}
From the "important segment" marked in the code, this is my output:
3200 before,
1059760811 after,
0.666667 (number returned by function)
Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.
I have no idea how to fix this, or what is going on. Help?!?!?
Thanks!
Looks like you may have a Stack Overflow issue in your enterdata function.
Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.
#WhozCraig is right, a stack overwrite by a called function seems the most likely explanation.
You should be able to find out in your debugger how to break on any change to the memory at address of z, this will quickly provide an exact diagnosis.
For Visual Studio (for example), see here.