occasional *** stack smashing detected*** with c++ - c++

I have following C++ code for bubble sort.
This code compiles without any error, but when I re compile and run, I get
*** stack smashing detected ***: terminated
As a C++ newby I want to know ,why do I get these occasional errors when it runs?
void bubbleSort(int eatenPanCakes[10],int arrSize){
int temp=0;
for(int i=0;i<arrSize-1;i++){
for (int j = 0; j < arrSize-i; j++)
{
if (eatenPanCakes[j] > eatenPanCakes[j+1])
{
temp = eatenPanCakes[j+1];
eatenPanCakes[j+1] = eatenPanCakes[j];
eatenPanCakes[j] = temp;
}
}
}
}
Environment : g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
There is a bug in my code : for (int j = 0; j+1 < arrSize-i; j++) would be the right algorithm and that works without error.
Ref-1,Ref-2

You program is accessing array beyond its size which is an undefined behavior. Check this for loop condition:
for (int j = 0; j < arrSize-i; j++)
[I believe, arrSize value is 10 as the type of eatenPanCakes array is int [10]].
when i is 0, arrSize-i value is 10 and in last iteration when j value is 9, this statement
if (eatenPanCakes[j] > eatenPanCakes[j+1])
access j+1th element of eatenPanCakes array which is element at index 10. Note that an array of size 10 will have valid index from 0 to 9.
Instead, the condition in for loop should be
for (int j = 0; j < arrSize - i - 1; j++)
^^^
because the jth element is compared with element ahead of it in the array.

Related

Array Sorting Issues in C++

I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++) {
for(int i = 0; i < size; i++) {
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
You are not looping correctly. Looks like you are trying bubble sort which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++)
for(int i = k+1; i < size; i++)
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(array[j]>array[j+1])
{
swap(array[j] , array[j+1]);
}
}
}
}
I see that you are trying to implement the bubble sort algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j and the element next to it at index j+1. If array[j] is greater than array[j+1] , you swap them using the swap() function or by using the temp method. The outer loop will run size - 1 times , and the inner loop will run size - 1 - i times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i . You can see the nested loop runs less number of times in each iteration of the outer loop.
There is only one mistake that your 2nd loop condition should be: i < size -1.
So it should be:
for (int i = 0; i < size -1; i++)
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1, therefore i + 1 is equal to size, thus data[i+1] is out of range. Simply change the condition of your for to be i < size - 1.
Working example: https://godbolt.org/z/e5ohWPfTz

Stack overflow when manipulating Bi-dimensional integer array

I wrote this C++ program to sort an integer matrix using selection sort. I tried to compile and run the program. But I ran into a stack overflow error and the message also said something about an access violation writing location .
I tried the following steps:
Tried reducing the array size from 50 x 50 to 10 x 10.
Tried heap allocation to the resultant array (using new).
Tried declaring the resultant array as static.
Tried examining the Memory option in Debug Menu for that particular memory
location(but couldn't make sense of it).
Tried examining the chkstk.asm file that the IDE automatically opened.
But all these efforts were of no use.
This is the part of the source code involved in the runtime error.
void SelectionSort(int matrix[][10], int rowMax, int colMax)
{
//Runtime error was pointed over here.
int smallest, temp, position, count = 0;
int resultant[10][10];
for (int row = 0; row < rowMax; row++)
{
for (int j = 0; j < rowMax - 1; j++)
{
smallest = matrix[row][j];
position = j;
for (int k = j + 1; k < rowMax; k++)
{
if (matrix[row][k] < smallest)
{
smallest = matrix[row][k];
position = k;
}
}
temp = matrix[row][j];
matrix[row][j] = matrix[row][position];
matrix[row][position] = temp;
}
}
for (int i = 0; i < rowMax; i++)
for (int j = 0; j < colMax; j++)
resultant[i][j] = matrix[j][i];
if (count == 0)
{
SelectionSort(resultant, rowMax, colMax);
count++;
}
else
{
std::cout << "The sorted matrix is: " << std::endl;
for (int i = 0; i < rowMax; i++)
{
for (int j = 0; j < colMax; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
}
}
These were the messages that were thrown.
Exception thrown at 0x00007FF79D763488 in Sorting Algorithm Benchmarking Program.exe: 0xC0000005: Access violation writing location 0x000000BFBF600000. occurred
and
Unhandled exception at 0x00007FF79D763488 in Sorting Algorithm Benchmarking Program.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000058CE0B3000). occurred
I expected the sorted matrix to be printed in the console.
For example, if the unsorted matrix is:
1 9 5
8 3 6
7 4 2
then the output should be:
1 2 3
4 5 6
7 8 9
I would request you not to send complicated template-based suggestions, as I am in the intermediate level of C++ programming.
Thanks in advance!

sort array without conditional

I need a program that sorts an array of integers without using conditional statements. Numbers are in the range from 0 to 100 and don't repeat.
#include <iostream>
using namespace std;
int main() {
int arr[] = { 34, 12, 24, 65, 63, 22 };
int arraySize = (sizeof(arr) / sizeof(*arr));
unsigned char buf[101] = { 0 };
for (int k = 0; k < arraySize; k++) {
buf[arr[k]]++;
}
unsigned char i = 0;
for (int k = 0; k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
for (int a : arr) {
cout << a << endl;
}
system("pause");
return 0;
}
This program works but I get the error after closing of the command prompt:
Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.
Is there a way to fix it?
The problem is that your code writes past the end of the array. It happens after you have encountered the last element in the counted sequence, but before the array buf has been exhausted, i.e.
for (int k = 0; k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
When you add the highest element, which is 65, to the result, i reaches 6, so assigning a[i] becomes illegal. See what's going on by adding an extra element to your array, setting it to -1, and watching what happens to it (it gets set to 100; demo 1).
You can fix it by adding an early exit condition to stop as soon as you filled the array back, i.e.
for (int k = 0; i < arraySize && k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
Now the -1 past the end of "active" part of our array remains -1 (demo).
The logic of the second loop is wrong. You have six numbers in arr, no doubles, which means that a total of six elements in buf will be set to 1.
That means that after a while, the value of i will be 6, which you then use as an index into arr, but index 6 is the seventh element in an array, leading you to write out of bounds.

error in two-dimensional array code

I wrote a multiplication table like this:
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int table[9][9], i, j;
for (i = 0; i < 10; ++i){
for (j = 0; j < 10; ++j)
{
table[i][j] = (i + 1) * (j + 1);
cout << table[i][j] << "\t";
}
cout << endl;
}
_getch();
return 0;
}
And when I run it it gives me the right answer but when I press a key it throws this error:
run time check faliure #2-stack around the variable table was corrupted
But it doesn't throw that error when I change the code to this:
......
int main(){
**int table[10][10]**, i, j;
for (i = 0; i < 10; ++i){
......
If they both give the same answer then what's the difference??
You are overflowing your arrays, The max index in bounds is 8 (since the indices are zero based and you defined 9 cells as your dimensions size so 8 will be the last cell in each dimension) and your for loop can reach till 9 (including 9) which will cause an overflow.
The snippet int table[9] declares an array of size 9, that means valid indices are actually 0-8. But your loop iterates from 0 to 9. This causes a write into an invalid memory region (which doesn't belong to your array), therefore corrupting your stack.
Now you actually have a two dimensional array, but the problem remains the same.
You're going outside the array in your for loops. They should be:
for (i = 0; i < 9; ++i){
for (j = 0; j < 9; ++j)
The array indexes run from 0 to 8, but you were going up to 9 because your conditions were i < 10 and j < 10.
Arrays in C/C++ start with 0 index.
When you declare table[9][9] you reserve memory for 9x9 array with indexes 0..8, 0..8
but in for loop your upper index is 9 - it is out of array range
I guess you should declare table like you pointed:
int table[10][10];
You are accessing out of array's range element.
Your array is a 9x9 table but you are trying to access 10x10 table.
So either use i<9 and j<9 in your both loops or increase your array size to table[10][10].
Hope this might help.
Rule of thumb: in for loops, N in (i = 0; i < N; i++) clause should (almost always) be equal to the corresponding array's length. When you see either i <= N or i < N + 1, it's (most often) a sign of the dreaded off-by-one bug.

Segmentation fault when implementing insertion sort

#include <iostream>
using namespace std;
int main(){
int a[6] = {5, 2, 4, 6, 1, 3}; // create an array of size 6
int j, key = 0;
for (int i = 1; i < 6; i++) {
key = a[i];
j = i - 1;
while ((j >= 0) && (a[j] > key)) {
a[j + 1] = a[j];
j -= 1;
}
a[j + 1] = key;
}
for (int l = 0; l < 6; l++) {
cout << a[l];
}
return 0;
}
I'm trying to test my insertion sort code using an array
the code complies but when I try to execute the a.out file,
it gives me "Segmentation Fault",
I look up what segmentation fault is, it's basically an error that we are trying to access the forbidden memory location, however, I'm wondering where exactly is the error in my code. Also, if i get rid of the
for (int l = 0; l < 6; l++) {
cout << a[l];
}
no error is found.
Your variable j is not initialized and so may be anything when you first access a[j]. That causes the segmentation fault. (int j,key =0; only sets key to 0 but not j.)
Always compile your code with -Wall, this would have told you about the use of the uninitialized variable. (Correction: My gcc 4.7 doesn't catch it. How lame.)
(The reason why the error goes away when you remove the printing is that you have compiler optimizations turned on: The compiler then notices that you never do anything practical with the computed values and arrays and just throws everything into the bin and gives you an empty program.)
sorting is one of the algorithms in the stl. you should really be using std::sort like
std::sort( a, a+6 );
PS: j is initialized before use in the line
j = i - 1;
so that is not the cause of the crash.