What is wrong with this simple char filler? - c++

It seems and looks really simple but a seemingly random spot of the char array is not filling correctly with 8's. There are no compiler errors either. I'm sorry that this is such a noob question but when I designed a sudoku solver a month ago I didn't have any problems running codes almost identical to this.
#include <iostream>
using namespace std;
int main () {
//Initiates initial board.
char board[30][27];
//Fills entire board with b's to represent the edges of the board where the pac-man cannot go.
for (int control=0; control<31; control++) {
for (int control2=0; control2<28; control2++) {
board[control][control2]='8';
}
}
//Code here filling the board with spaces representing where the pac-man can go.
//Temporary render of board.
for (int control=0; control<31; control++) {
for (int control2=0; control2<28; control2++) {
cout << board[control][control2];
}
cout << endl;
}
return 0;
}
It apparently has a random segmentation fault.

The segmentation fault is hardly random. You're overrunning the bounds of your array. board[30] and board[][28] are each one past the end of their respective dimensions. In this case, you're probably overwriting the return address from main(), so your program goes off into the weeds and then dies a horrible death like you're seeing in the segmentation fault. Change your loop conditions to:
control < 30
and
control2 < 27
And you should be fine. You could also change your array's size to board[31][28].
Most importantly, you should also learn to use a debugger, which you could use to find the values of the control and control2 variables at the time of failure, which would have solved this problem for you without having to ask here.

You are indexing past the maximum of the array.
The maximum index you can do on board is board[29][26], because the 30 and 27 you have put are the number of elements and arrays are zero indexed.

You're exceeding the size of your matrix. You have:
char board[30][27];
But your loops are:
for (int control=0; control<31; control++) {
for (int control2=0; control2<28; control2++) {
They will overshoot each dimension by 1.
So either change your matrix to: char board[31][28]; or cut an iteration off of your loops.

Related

C++ Dynamic bool array causes crash

Today I tried to program the Sieve of Eratosthenes and it works as far as it provides me with the prime numbers. But I have a problem with the dynamic array I don't understand.
First problem: As soon as I try to enter a "big" value for n (for example 120), the program crashes, it doesn't even allocate the memory.
Second problem: If I enter a value like 50 it is able to give out the correct prime numbers but crashes before it deletes the array.
Third problem: If I enter a very small value like 5 it is able to execute the entire program, it gives out the correct numbers and deletes the memory.
But I don't understand why it acts so differently. 120 boolean values can't crash my memory, at least I think so. And why isn't it able to delete an array of 50 values but is actually able to delete an array of 5 values?
Can anyone tell me what's the problem?
int n;
cin >> n;
n=n+1;
bool *feld = new bool[n];
for(int i=2;i<n;i++)
{
int j=i*i;
feld[j]=true;
for(;j<n;j+=i)
feld[j]=true;
}
for(int i=2;i<n;i++)
if(!feld[i])
cout << i << endl;
else;
delete[] feld;
feld = NULL;
Your problem is here:
int j=i*i;
feld[j]=true;
there is no check as to whether j < n so you are stomping over unallocated memory when j >= n.
This code is wrong
bool *feld = new bool[n];
for(int i=2;i<n;i++)
{
int j=i*i;
feld[j]=true;
...
}
Suppose n == 10 and i == 9, then j == 81 but you only have 10 elements in your bool array.
This is how it works when you write bugged programs, sometimes it seems to work, it might even give the right answer, other times it will crash. This is a very important lesson, and you're actually lucky to have learned it early.
Actually It's not just that feld[j]=true; is causing the error.
Also, you don't need that line at all before the loop.
because, it's the first case inside the loop.

Print statement changing output of function?

I have a bit of c++ code that's supposed to look at the derivative of a function and collect the points that have a slope greater than some threshold. It's been giving me troubles, so I've been putting print statements everywhere to figure out what is going wrong. I stumbled upon a baffling issue where when I used std::cout<< to print the size of an array, it changed the output of the function! Here's the code snippet:
int* Tools::findPoi(float* y, int size, float threshold, int width, float step, int* outsize){
int poi[size];
float* derive = derivative(smooth(y,size,width),size, step);
int n = 0;
std::cout<<size<<" data size\n";
for(int i = 0; i<size; i++) {
if(derive[i] > threshold) {
poi[n] = i;
n++;
}
}
*outsize = n-1;
return poi;
}
without the commented out line "std::count..." I get 82 poi. But if I comment it out or remove it I get 84 poi. Nothing else changes, only this print statement. I am so confused as to why or even how it could possibly change the output. Any help would be greatly appreciated.
EDIT: ok, so actually, it's just random. The variable n is different everytime I run it, which leads me to believe that something weird is going on in memory.
There is a significant problem with the line:
return poi;
This returns the address of a local object. The array no longer exists when it goes out of scope at the end of the function. For a wonderful explanation see: Can a local variable's memory be accessed outside its scope?.
Since this is C++ and you want a dynamic array I suggest you use std::vector. It solves many problems such as this.

How can I properly set a condition for an specific space in array?

I'm Developing an small app for practice purposes in C++, I actually suceeded developing this algorithm without using arrays, but right now I want to do it using an Array. The program should accept four grades 2 of 15 points practices (First and third value), two of 20 points (Second and fourth values) and one of 30 points. this is my code:
int main(int argc, char** argv){
int grades[5];
int i;
int sum=0;
for(i=0; i<5; i++){
cin >> grades[i];
sum+=grades[i];
if(grades[0]>15||grades[1]>20){
cout<<"ERROR"<<endl;
break;
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}if(grades[4]>30){
cout <<"ERROR"<<endl;
break;
}
}
}
The issue here is that it should not be printing Error on console and break it from continuing, only if the condition is met, at this point if I input values even within the condition's grace, it prints out "Error" and stops.
I'm not really looking for someone to solve this issue, I'm looking to know what I'm doing wrong without getting someone to solve it for me, in proper words, I'm looking for tips/hints.
This line here
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}
will cause your error to display at any time your elements at indices 2 or 3 are non zero. You dont initialise your array elements so it is quite possible that the values are nonzero when your loop starts. To ensure that they are not, you could assign zero to all elements before you start. I am not sure what your code is trying to do, but when the user enters anything other than zero for the cin at i = 2 and i = 3 your loop will break with error output (assuming that the first if confition in your if-else block is not satisfied but if that condition was satisfied your loop would also exit anyway)

topological sorting using dfs

here is topological sorting using DFS in c++,which has bugs(out of bound error)
#include<iostream>
#include<stdio.h>
using namespace std;
int count=0;
static int *a=new int[8];
void dfs(int u,bool v[],bool matrix[][8])
{
v[u]=true;
for(int i=0;i<8;i++)
if(!v[i]&& matrix[u][i])
dfs(i,v,matrix);
a[count++]=u;
}
int main()
{
bool v[8];
bool matrix[8][8];
matrix[7][6]=true;
matrix[0][1];
matrix[1][2]=true;
matrix[2][3]=true;
matrix[3][4]=true;
matrix[2][5]=true;
for(int i=0;i<8;i++)
if(!v[i])
dfs(i,v,matrix);
for(int i=0;i<8;i++)
cout<<a[7-i]<<" ";
}
please help me to fix this error,i think i should create matrix[8][2],but how to continue after that?
I have done a few changes and now your program finishes successfully on ideone
The most significant change is that you did not initialize matrix and v(even without this change the program still finished successfully but the output was only 0-s). I did not see the error you are talking about. The reason for getting only 0-s when you did not initialize v is obvious - all the values where non-zero and so all nodes where considered not visited.
EDIT: I also changed line 27 where you seemed to have forgotten " = true;"
EDIT 2: you are not freeing the memory for a which is not good. Also I don't see why you need dynamic array for a. You know its size aforehand. And one last remark - if you make the arrays matrix and v global they will get zeroed automatically(I am not saying that this is good approach just pointing out), but as they are local they are not zeroed.

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;