nup
nup

Reputation: 61

Why don't my loop of incrementing pointer end but cut off and printing weird output?

I'm new to coding with pointers. This is my code.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    int a = 1;
    int* p = &a;

    for (int i = 0;i < 10; i++) {
        p++;
        *(p) = rand() % 10 + 1;
        cout << p << " " << *p << endl;
    }
}

Somehow, the code keeps ending before the loop end and print out a series of address but then in the last address end with 03. Can anyone help I search all over but nothing. output:

00000073532FF808 2
00000073532FF80C 8
00000073532FF810 5
00000073532FF814 1
00000073532FF818 10
00000073532FF81C 5
00000073532FF820 9
00000073532FF824 9
0000007300000003

Upvotes: 1

Views: 44

Answers (1)

Scheff&#39;s Cat
Scheff&#39;s Cat

Reputation: 20171

First, there is allocated storage for one int.

    int a = 1;

Second a pointer which points to this storage.

    int *p = &a;

Now, writing to *p will modify a but...

    for (int i = 0;i < 10; i++) {
        p++;
        *(p) = rand() % 10 + 1;

i.e. p is incremented.

Even in the first loop it now points to memory beyond a.

That memory is either allocated for something else, or used for something else, or not allocated at all. In any case, this is Undefined Behavior i.e. writing out of bounds.

That's the nature of Undefined Behavior that everything is possible now—no predictions can be made anymore what will happen.

If the loop terminates before 10 iterations are done I suspect that i might be corrupted by this. It's also possible that p corrupts itself. This doesn't change the fact that it's Undefined Behavior.


A possible fix of OPs application would be to provide sufficient storage in a where p can be iterated over without going out-of-bounds.

For this, the definitions at the beginning of main() had to be changed to:

    int a[11] = { 1 };
    int* p = a; // could also be: int* p = &a[0];

Please, note that p is incremented before writing to it. Hence, in the last iteration (with i = 9), p will point to a[10] before the write access. Therefore, the minimal sufficient array size is int a[11] instead of int a[10] which someone might think from the first glance.


The fixed program of OP:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int a[11] = { 1 };
    int* p = a;

    for (int i = 0;i < 10; i++) {
        p++;
        *(p) = rand() % 10 + 1;
        cout << p << " " << *p << endl;
    }
    // double check
    cout << "a:";
    for (int value : a) cout << ' ' << value;
    cout << endl;
}

Output:

0x7fff57151bc4 4
0x7fff57151bc8 7
0x7fff57151bcc 8
0x7fff57151bd0 6
0x7fff57151bd4 4
0x7fff57151bd8 6
0x7fff57151bdc 7
0x7fff57151be0 3
0x7fff57151be4 10
0x7fff57151be8 2
a: 1 4 7 8 6 4 6 7 3 10 2

Live Demo on coliru

Upvotes: 1

Related Questions