cockroach man
cockroach man

Reputation: 17

Why does this C++ function not output what I want?

#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?

Upvotes: 0

Views: 93

Answers (1)

PFee
PFee

Reputation: 273

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

Upvotes: 2

Related Questions