STATUS_STACK_BUFFER_OVERRUN encountered - c++

I have searched for this particular error and found the underlying issue involves loop counts being wrong and causing the program to exceed it's bounds for the array.
However, after I lowered each array to the point where the array began to lose data on output, it continued to throw the same error. I am still new to C/C++ but any insight into this would be greatly appreciated.
The program seems to run through to the very end and even returns to the main method.
#include <stdio.h>
void sortAr(char[]);
int main ()
{
char a='y';
char b,i;
char c[20];
int x=0,n=0,z=0;
while (x<=19)
{
c[x]='#';
x++;
}
printf("Enter 20 letters: \n");
while (z<=20) //(The '=' caused my problem, removed and it runs fine.)
{
z++;
x=0;
b='y';
scanf("%c",&i);
while (x<=19)
{
if (c[x]==i)
b='n';
x++;
}
if (b=='y')
{
c[n]=i;
n++;
}
}
printf("\n");
printf("The nonduplicate values are: \n");
sortAr(c);
}
void sortAr(char ar[])
{
char z;
for (int i = 0; i <= 19; i++)
{
for (int j=i+1; j <= 19; ++j)
{
if (ar[i]>ar[j])
{
z = ar[i];
ar[i] = ar[j];
ar[j] = z;
}
}
}
for (int i = 0; i < 20; i++)
{
if(ar[i]=='#')
continue;
printf("%c ", ar[i]);
}
printf("\n");
}

I found the error at:
while (z<=20)
The reason is the array would overwrite more characters than intended by executing more times than the array had indexed in the memory. As a result it wrote into memory that was not allocated to it and caused the Stack_Buffer_Overrun.
Trace Z:
Z was initialized to 0.
Array was initialized to 20.
While loop starts with Z as the counter for read-ins.
z=0 array=1 1st run,
z=1 array=2 2nd run,
z=2 array=3 3rd run,
z=3 array=4 4th run,
...
z=20 array=21 21st run. (Array cannot hold 21st character and results in Stack_Buffer_Overrun.)
Solution:
change while(z<=20) -> while(z<20)

Related

"void value not ignored as it ought to be" When trying to sort an array

I'm new to programming and trying to program a sensor. I'm sorting the array that I plot the input from the sensor into. But I'm running into a problem when sorting it, it gives me this error:
exit status 1
void value not ignored as it ought to be"
Here's my code:
#include <ArduinoSort.h>
int a[10];
int b[10];
int sensor1 = A0;
int sensor2 = A1;
int display1;
int display2;
int sort[10];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
delay(100);
Serial.print("Sensor 1: [");
for (int i = 0; i < 11; i++) {
display1 = analogRead(sensor1);
a[i] = display1;
sort[i] = sortArray(a, 10);
if (i < 10) {
Serial.print(String(sort[i]) + ",");
} else {
Serial.print(String(sort[i]));
}
}
Serial.print("]");
Serial.println();
Serial.print("Sensor 2: [");
for (int i = 0; i < 11; i++) {
display2 = analogRead(sensor2);
b[i] = display2;
if (i < 10) {
Serial.print(String(b[i]) + ",");
} else {
Serial.print(String(b[i]));
}
}
Serial.print("]");
Serial.println();
Serial.println();
//String hej = "Sensor 1"+ String(display1);
//Serial.println(hej);
}
and, on this line I get the error:
sort[i] = sortArray(a,10);
The sortArray() function returns nothing i.e. void.
It sorts the passed array in-place so you need to call it like this:
sortArray(a, 10); // no return value assignment
As pointed out by Ben Voigt, you have not initialized a properly so you need to first collect all the values and then sort it after the loop.
Here's your loop (after correction of sortArray after loop):
for (int i = 0; i < 11; i++) { // 0-10 i.e. 11 iterations
a[i] = analogRead(sensor1); // read values in the array
// ...
}
sortArray(a, 10); // sort after the loop
Another problem is that your loop's condition is i < 11 which means the iterations from 0 to 10 i.e. 11 iterations. But, the arrays you're using are of size 10 i.e. 0 to 9 locations as C++ arrays are ZERO-based. So, this is causing out-of-bounds access resulting in Undefined Behavior.
So, your loop iterations and the array sizes should match i.e. 10 iterations and 10 memory locations to write to.
It's better to use a constant and use that at all places like this:
const int SIZE = 10;
int a[SIZE] = {0}; // initialize if it's not an overhead for arduino
for (int i = 0; i < SIZE; i++) {
a[i] = analogRead(sensor1);
// ...
}
sortArray(a, SIZE);
You have a somewhat bigger problem with this code.
You simply cannot "print outputs in sorted order" while you are still collecting them. You don't know whether the "smallest" right now should be printed, or wait because an even smaller one is forthcoming.

program for n-queens problem only works for n<=10 even though it should work for all n

The n-queens problem asks how many different ways are there to put n queens on a n-by-n board such that the queens cannot attack each other in one move. I've written a program which partially solves this problem. I say partially because my program only works for n<=10. However, I did not specify or hard-code the value 10, or any other value, in my code.
For example, my code outputs 92 solutions for 8-by-8, 352 for 9-by-9, and 724 for 10-by-10. These are the expected values as stated on the n-queens wikipedia page. However, my code outputs 1649 for 11-by-11. The expected answer is 2,680.
I really have no idea why this would occur.
using namespace std;
class Board{
struct Position{
int r;
int c;
};
public:
int size;
vector<vector<int> > b;
Position pos;
vector<int> placements;
int count;
Board(int s){
size=s;
pos.r=0;
pos.c=0;
for(int i=0; i<s; i++){
b.push_back(vector<int>());
for(int j=0; j<s; j++){
b.at(i).push_back(0);
}
}
count=0;
}
bool hasQueens(){
for(int i=0; size-i>=0; i++){
if(b[pos.r][pos.c-i]==1){
return true;
}
if(pos.r-i >= 0){
if(b[pos.r-i][pos.c-i]==1){
return true;
}
}
if(pos.r+i < size){
if(b[pos.r+i][pos.c-i]==1){
return true;
}
}
}
return false;
}
void placeQueen(){
b[pos.r][pos.c]=1;
placements.push_back(pos.r);
}
void backtrack(){
pos.c--;
b[placements[pos.c]][pos.c]=0;
pos.r = placements[pos.c] +1;
placements.pop_back();
if(pos.r==size) backtrack();
}
bool canBacktrack(){
if(pos.c==1 && placements[0]==size-1) return false;
else return true;
}
void nextSol(){
while(pos.c!=size){ //while the board is not filled
if(pos.r==size && canBacktrack()){
backtrack();
} else if(pos.r==size && !canBacktrack()){
break;
}else if(!hasQueens()){
placeQueen();
pos.r=0;
pos.c++;
} else {
pos.r++;
}
}
}
void print(){
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
cout << b[i][j];
}
cout<<endl;
}
cout<<endl;
}
};
int main(){
Board board(11);
board.print();
while(true){
board.nextSol();
if(!board.canBacktrack()) break;
cout << ++board.count << endl;
board.backtrack();
}
}
Your code segfaults for me. Running it through valgrind says that there is invalid read in this line:
if(b[pos.r][pos.c-i]==1){
in function hasQueens(). And indeed, there are cases in which pos.c-i becomes negative: whenever pos.c is smaller than size.
The organization of the code is messy, I would suggest to write your boundaries out clearly instead of relying on stopping for col == 1 and r == size (which if access incorrectly can cause a segfault). Also, NQueen problem has an elegant solution with recursion, I would suggest to look into that as well.
I was able to make some changes to your program and got the expected answer for 11 x 11, however I think there are more bugs in the code. The problem lies in the backtrack() and placeQueen() function, pos.c is decremented without checking if it's greater than 0, so it can potentially go negative and crash when access. Most importantly you don't need to do push_back/pop_back on the placement vector since you know you only can place one queen on each column so it should really be fixed size. when placing queen, you can do placement[c] = r. Hope this helps.

C++ STL stack pop operation giving Segment fault though I checked for empty stack

I performed the pop operation on S[position] stack and it's giving segment fault but the top operation giving the result without any error and the empty check also performed before the pop operation.
Can't figure out what is causing the problem.
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;
int main(){
int bar,position;
cout<<"Enter the number of bars: ";cin>>bar;
cout<<"Enter the position of the bar where you want to place: ";cin>>position;
position = position - 1;
stack<int> S[bar];
for(int i = bar; i>0; i--){
S[0].push(i);
}
S[0].pop();
for(int i = 1; i<bar; i++){
if(i == position){
S[i].push(1);
continue;
}
S[i].push(S[0].top());
S[0].pop();
}
for(int i = 1; i< bar; i++){
if(S[i].top() == 2){
if(!S[position].empty()){
cout<<S[position].top();
S[position].pop(); //This line generating segment fault
}
}
}
}
Output:
Enter the number of bars: 3
Enter the position of the bar where you want to place: 2
Segmentation fault (core dumped)
1.You can use one library - bits/stdc++.h. This lib contains almost everyone lib.
#include <bits/stdc++.h>
2.If bars=b, stack have k elements, 0 - k-1, and you go in 1. You must go on 0, or make stack with k+1 elements.
stack<int> s[k+1] and for(long long i=1 ; i<=bar ; i++);
or
for(i=0 ; i<bars ; i++)
3.The real error - the one you are looking for is not on the order in which you think. The error is on line when you make check for its value.
line:
if(S[i].top() == 2)
The error is here, because you are not sure are this stack empty. You check for stack[position]. If stack is empty and you get .pop() or .top() the compiler give you Segmentation fault (core dumped).
In my opinion you are confused about where to write i and position, but check -!S[i].empty() must be before if(S[i] == 2). Or you just need to check the stack with index i if it's empty. After the changes, the code look like this:
#include<bits/stdc++.h>
using namespace std;
int main(){
int bar,position;
cout<<"Enter the number of bars: ";cin>>bar;
cout<<"Enter the position of the bar where you want to place: ";cin>>position;
position = position - 1;
stack<int> S[bar];
for(int i = bar; i>0; i--){
S[0].push(i);
}
S[0].pop();
for(int i = 0; i<bar; i++){
if(i == position){
S[i].push(1);
continue;
}
S[i].push(S[0].top());
S[0].pop();
}
/*
for(int i = 0; i < bar; i++){
if( !S[i].empty() ){
if(S[i].top() == 2){
cout<<S[i].top();
S[i].pop();
}
}
}
OR
*/
for(int i = 0; i < bar; i++){
if( !S[i].empty() ){
if(S[i].top() == 2){///this line gave you a segmentation fault (core dumped)
if(!S[position].empty()){
cout<<S[position].top();
S[position].pop();
}
}
}
}
return 0;
}

SIGABRT error in C++

I am getting a SIGABRT error when I compile the following code.(PRIME1 problem of spoj).
Link of the problem is http://www.spoj.com/problems/PRIME1/. It runs well on codeblocks but spoj returns SIGABRT error. Can someone explain the reason?
int main()
{
long long k,x,j=0,size,l=0,p=0,q=0,r=0,s;
cin>>size;
int a[(2*size)];
cout<<endl;
for(int i=0; i< (2*size); i++)
{
cin>>a[i];
}
if( size == 1)
{
p=a[1];
}
else
{
do
{
if(a[l+3]>a[l+1])
{
p=a[l+3];
}
else
{
p=a[l+1];
}
l=l+2;
}while(l<2*(size-1));
}
cout<<p;
long * b = new long [p-1];
for(long long i=0;i<p-1;i++)
{
b[i]=1;
}
b[0]=b[1]=0;
s=sqrt(p)
for(long long i = 2; i <= s; i++)
{
if(b[i] == 1)
{
for(long long j = i*i; j <= p; j = j + i)
{
b[j] = 0;
}
}
}
while(r<(2*size))
{
for(long long i = a[r];i < a[r+1];i++)
{
if(b[i] == 1 )
{
cout << i << "\n";
}
}
cout<<endl;
r=r+2;
}
delete [] b;
}
You are accessing array element accessing outside bounds
Array size 2*size-1 So elements from 0 to 2*size-2
But in your for loop you are going upto 2*size thus accessing 2*size-1 which is outside bounds
int a[(2*size)-1];
This is not legal C++ code (it's using a GCC extension), but it obviously compiled, so we'll let that slide. You are accessing your array out of bounds in the following loop and all over the place later on, which is undefined behavior - you need an array of size 2 * size to read in all the supplied parameters. Although given that they guarantee that size <= 10, you might as well just declare it as int a[20];
But that probably didn't cause the crash. What caused the crash is probably this line:
long * b = new long [p-1];
What's p? Well, let's just consider the easy case of size = 1 where you set p to a[1], or the second number you read in. What's the bounds on that number?
The questions says that the bound is n <= 1000000000, or 109. Your new can be requesting as much as 8GB of memory, depending on the value of sizeof(long) in the system you are using. The allocation is almost certainly going to fail, throwing a std::bad_alloc exception that causes std::abort() to be called as you don't have any exception handling code.
You initialize a to 2 * size - 1 elements...
int a[(2*size)-1];
Yet you write 2 * size elements.
for(int i=0; i< (2*size); i++)
// ...
Your loop should be:
for(int i=0; i< (2*size-1); i++)
Next...
if(size == 1)
{
p=a[1];
}
If size == 1 then you allocated an array of 2 * 1 - 1 = 1 element, so a[1] is an invalid access (you only have a[0] as arrays are 0-indexed).
You then have stuff like this:
if(a[l+3]>a[l+1])
Which loops until l == 2*size-1, so l+3 is invalid as soon as you hit 2 * size - 1 - 3.
Basically you just have a lot of places where you're reading or writing past the end of an array or not ensuring proper initialization and invoking undefined behavior.

Dynamic matrix in c/c++ - peculiar error

I was trying to write a small program with a dynamical matrix ( I started it in C, but now I see I need to do it in C++). the main part of it looked like this:
int main()
{
int n,m,i,j,k;
printf("Matrix A n x m:\n");
printf("Input n: ");
scanf("%d",&n);
printf("Input m: ");
scanf("%d",&m);
int** matrix = new int*[m];
if (matrix == NULL) {
printf("no memory\n");
system("pause");
exit(1);
}
for(k=0; k<m; ++k)
{
matrix[k]=new int[n];
if(matrix[k]==NULL)
{
printf("error");
}
}
j=0;
do
{
i=0;
do
{
printf("input (%d,%d):", i,j);
scanf("%d", &matrix[i][j]);
i++;
}
while (i<n);
j++;
}
while (j<m);
}
It compiles with no error, but it doesn't work properly. For example, I can create 2x4 matrix, but no 4x2. After The Input (3,0) message appears, the program crashes. Why?
you mixed between i and j, you should do scanf("%d", &matrix[j][i]);
Your i and j values are the wrong way round. j goes from 0..m-1, i goes from 0..n-1. Your input should be fore &matrix[j][i]. Either that or change the while loops to i < m and j < n.
As I understand it an array must have at least 1 element, if you are compiling in strict ANSI mode.
int m[]; /*ILLEGAL*/
int m[0]; /* definition of 0 size -- ILLEGAL */
please correct me if I am incorrect
You must declare the array element to have (at least) one element if you are compiling in strict ANSI mode
kind regards