Why am I getting segmentation fault error? [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 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.

Related

Expected Primary expression before int inside a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 12 months ago.
Improve this question
I am very aware that a lot of the formatting of this code is likely to be completely wrong. I am attempting to create a function GenPathByNumber which itself calls a function Binary. The GenPathBynumber attempts to (for integer x values from 0 through to 2^N - 1) create an array Path for each x value, with entries corresponding to each digit of x's binary representation. Binary converts each x to its binary reresentation, and GenPathByNumber puts binary through a loop.
When trying to build this, the logs keep saying "Expected Primary expression before int" for the Binary function (line 10 in the code below). Please can someone tell me what the problem(s) are?
void GenPathByNumber(int x,int N,int *Path)
{
//Create the array Path of length N, with all entries set to 0
Path[N] = {0};
//runs a for loop of all x values up to 2^N - 1
//and generates a binary path corresponding to each number
// of length N, then stores each digit of this in array Path.
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
}
void binary(int x, int* Path) {
if (x == 0) {
printf("%s\n", Path);
} else {
Path[x-1]='0';
binary(x-1);
Path[x-1] = '1';
binary(x-1);
}
}
Inside the for loop in GenPathByNumber you have:
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
You don't need the argument type specifiers when you call a function, only when you define it. Remove those and the error goes away.
binary(x, Path);
You have other errors inside the binary function where you're calling it with only one argument, like binary(x - 1);. You probably mean to provide Path in those calls as well.

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.

Cpp - EXC_BAD_ACCESS in recursion [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
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.

Unexpected changing of C++ constant integer [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 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

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.