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.
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+1
th 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 j
th element is compared with element ahead of it in the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.