0

I am not getting any of bounds errors or segmentation fault, and I do see from people's comments that this is common. But is there a way to get the compiler to issue an error instead of opening my program to possible undefined behavior?

#include <iostream>
#define MAX 10

int main(void){

    int A[MAX] = {9, 3, 9, 3, 9, 3, 0, 0, 9, 3};
    int C[10];
    int B[MAX] = {0};

    for (int i = 0; i < 10; i++)    C[i] = 0;

    //  increment count of buckets containing this digit accordingly
    for (int i = 0; i < MAX; i++)   C[A[i]] =  C[A[i]] + 1;

    //  count all count <= the current bucket to determine the correct index
    for (int i = 1; i < 10; i++)    C[i] = C[i] + C[i-1];

    //  copy the correct array element to output array B and decrement C array accordingly
    for (int i = MAX-1; i >= 0; i--){
        B[C[A[i]]] = A[i];
        C[A[i]] = C[A[i]]-1;
    }

    std::cout << "\nSorted array = ";
    for (int i = 1; i <= MAX; i++)  std::cout << " " << B[i] << " ";
    std::cout << "\n";

    return 0;
}
Jeff
  • 11
  • 3
  • 1
    C++ doesn't have any bound-checking. Indexing an array out of bounds leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) which in some cases can cause a crash or sometimes can [summon nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude Sep 02 '19 at 06:59
  • There is no guarantee of diagnostic if you read outside of object and you may end with smashed stack if you write beyond one with non-static lifespan. Or worse. It's not defined. – Swift - Friday Pie Sep 02 '19 at 07:01

1 Answers1

-2

Nobody promised you will get a SegFault every time you access the arrays out of bounds. Some data structures will give you an exception (std::vector, for example), if you try v.at(MAX).

Still, your program usually has a lot of memory, and accessing v[MAX] is just accessing the next variable, like, it's very well known trick to do:

int a[10], b[10], c[10];

for( int i=0; i<30; i++) a[i] = 0;  // zero THEM ALL

To get a SegFault reliably you have to access NULL pointer or something totally out if your program memory area.

lenik
  • 23,228
  • 4
  • 34
  • 43
  • 4
    "To get a SegFault reliably you have to access NULL pointer" - huh? That's merely undefined behaviour too. – Bathsheba Sep 02 '19 at 07:10
  • Truly, [dereferencing null pointers causing segfaults](https://rextester.com/QNOCD25068) is the most reliable of behaviours. – Justin Time - Reinstate Monica Sep 02 '19 at 18:45
  • "`// zero THEM ALL`" - well, yeah, there is no guarantee that it will work, even if it currently works on all the major compilers. They are free to assume that there is no UB in the code and they are free to change the orders of the variables. You cannot rely that `int a[10], b[10], c[10];` will place `a` on the stack followed by `b` and `c`. – Fureeish Sep 02 '19 at 20:06