-1

I have this code

int main()
{
    int arr[]={1,2,3,4,5,6,8,10,12,14};
    int n=sizeof(arr)/sizeof(arr[0]);
    int array[n];
    int x=n;

    while(x>0){
        arr[x]=0;
        x--;
    }

    return 0;
}

Basically I am getting error

** stack smashing detected ***: terminated
Aborted (core dumped)

when debugging in gdb I found when x reaches value 2 in while loop then it does not decrease and value stays at 2 means there is no outcome of statement x--; in the while loop. why is this but when I do code while loop like this

 while(x-->0){
        arr[x]=0;
 }

error goes away. What's happening there and why is not happening anymore

int main()
{
    int arr[]={1,2,3,4,5,6,8,10,12,14};
    int n=sizeof(arr)/sizeof(arr[0]);
    int array[n];
    int x=n;
    while(x>0){
        arr[x]=0;
        x--;
    }

    return 0;
}
klutt
  • 30,332
  • 17
  • 55
  • 95
user786
  • 3,902
  • 4
  • 40
  • 72
  • 2
    `arr[x]` is UB on the first iteration. Decrement first, then assign – Mad Physicist Aug 17 '21 at 05:29
  • @MadPhysicist yes this fixed the problem . thanks what is UB? – user786 Aug 17 '21 at 05:43
  • @user786 [UB = undefined behavior](https://stackoverflow.com/q/2397984/6699433) – klutt Aug 17 '21 at 05:55
  • UB is "undefined behaviour". The C standard does not define how a program with such statements or expressions behaves. Anything can happen, including [_demons flying out of your nose_](http://catb.org/jargon/html/N/nasal-demons.html). – the busybee Aug 17 '21 at 05:57

1 Answers1

2

You exceed the bounds of arr. If n is 3, arr has three entries, but you access arr[3]. Since arr[0] is the first entry, arr[3] is the fourth entry. An array with three entries has no fourth entry.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • `An array with three entries has no fourth entry.` can u also please relate this to why x is not decrementing because of `...has no fourth entry` – user786 Aug 17 '21 at 05:41
  • 1
    @user786 The code has a bug. You have to fix the bug. It really is that simple. Your code will behave in strange and unpredictable ways if you smash the stack -- it will not, in general, be possible to understand them without a *lot* more details. (What platform? What compiler? What compiler options? Etcetera.) – David Schwartz Aug 17 '21 at 05:46
  • 1
    @user786. As an arbitrary example, you declare `array`, then `x`, so it's conceivable that the compiler places them on the stack in that order. Writing past the end of `array` will then overwrite `x`. I'm not saying that's what's happening in this case: it's just to give you an idea of the sort of thing that could be happening. – Mad Physicist Aug 17 '21 at 12:17
  • make sense now could be – user786 Aug 17 '21 at 12:27
  • make sense now could be in case if I was writing to `array[n]` array – user786 Aug 17 '21 at 12:44