1

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

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94

1 Answers1

3

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.

H.S.
  • 11,654
  • 2
  • 15
  • 32
  • Yes, thanks for detailed explanation. But my problem is, this happens **occasionally**. Sometimes, it runs without `coredump` – Sachith Muhandiram Jan 31 '21 at 02:19
  • 1
    @SachithMuhandiram This is due to undefined behaviour. An undefined behaviour includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended. – H.S. Jan 31 '21 at 02:42