Day#113 C coding challenge | Find the Bug in the below Code

Day#113 C coding challenge | Find the Bug in the below Code

Find the bug in the below C code snippet


The issue lies in this loop condition:

for (int i = 0; i <= n; i++)  // There is a BUG here

In the above program, if n = 5, then the loop runs from i = 0 to i = 5 inclusive, i.e., 6 iterations.
But the array numbers[] has only 5 elements.

int numbers[] = {1, 2, 3, 4, 5};  // indexes only from 0 to 4 and no 5
So error is: arr[5] is out of bounds – reading invalid memory (undefined behavior).

Explanation here: https://youtu.be/mm60cyXDjWw

Post a Comment

0 Comments