0
#include <iostream.h>
using namespace std;

int main() {
    int i, n = 5, k, a;

    cin >> k;
    cin >> a;

    int v[] = { 1,2,3,4,5 };

    for (i = 0; i < n; i++) {
        v[i] = i + 1;
    }

    for (i = n; i >= k - 1; i--) {
        v[i + 1] = v[i];
    }

    v[k - 1] = a;

    for (i = 0; i < n + 1; i++) {
        cout << v[i] << " ";
    }

    return 0;
}

k = 2 and a = 10

It seems that the vector output should be "1 10 2 3 4 5", but when I run it, the output is "1 2 3 4 5 10".

Why is that?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 3
    [Please do not post images of code because they are hard to use.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) Code should be posted directly **as text** in your question. – MikeCAT Apr 12 '21 at 13:25
  • [`` is not a standard C++ header.](https://stackoverflow.com/q/2976477/13188071) – mediocrevegetable1 Apr 12 '21 at 13:26
  • 3
    `i=n; v[i+1]` Out-of-range access here. – MikeCAT Apr 12 '21 at 13:29
  • ***v[k - 1] = a;*** Is k always greater than 1 and less than or equal to 5? – drescherjm Apr 12 '21 at 13:41
  • The array has five elements, and your second loop begins with assigning the value of the sixth element to the seventh, neither of which exist, and that has undefined behaviour. You can't add elements to an array. – molbdnilo Apr 12 '21 at 13:51
  • 2
    Use `v.at(foo)` rather than `v[foo]` unless performance really matters. Then at least you get an exception if you access out of range. I've just fixed a production bug (marked 'highest' in our issue tracking system) that was down to out of range `std::vector` access. Try to avoid that. 'highest' in my shop means fix immediately. – Bathsheba Apr 12 '21 at 14:20

1 Answers1

2

The first loop is redundant, v is already set to { 1, 2, 3, 4, 5}.

The second loop has a buffer overflow. "i" starts at 5, so v[i+1] tries to access the sixth array element, however the array has only indexes zero to four (five elements).

Finally, for the "v[k - 1] = a" statement, since k=2 and a=10, this puts 10 at index 1.

Result: 1, 10, 2, 3, 4.

Incidentally, try running your code via GCC or Clang's sanitizer. These will spot the buffer overflow in your code.

$ c++ -fsanitize=address -g example.cpp
$ ./a.out
<snip>
SUMMARY: AddressSanitizer: stack-buffer-overflow example.cpp:17 in main
PFee
  • 249
  • 2
  • 10