-2

First off, This is a question about the compiler behavior not to correct the code either!

Here's my code but I cannot explain it to myself why I've got this results. I know it has a memory error (deleting pointer in other scope and before done with it) however the results only for the last element get problematic. Why the last element only has the raw generated rand number?

#include <iostream>

using namespace std;

void populate(int *arrayToPopulate, int arraySize);

int main() {
    int *ptr;
    ptr = new int[100];

    populate(ptr, 100);

    for (int i = 0; i < 100; i++)
        cout << ptr[i] << endl;

    return 0;
}

void populate(int *arr, int size) {
    for (int i = 0; i < size; i++) {

        arr[i] = rand() % 100 + 1;
    }

    delete [] arr;
}

The results:

8 50 74 59 31 73 45 79 24 10 41 66 93 43 88 4 28 30 41 13 4 70 10 58 61 34 100 79 17 36 98 27 13 68 11 34 80 50 80 22 68 73 94 37 86 46 29 92 95 58 2 54 9 45 69 91 25 97 31 4 23 67 50 25 2 54 78 9 29 34 99 82 36 14 66 15 64 37 26 70 16 95 30 2 18 96 6 5 52 99 89 24 6 83 53 67 17 38 39 2687021

Shayan Amani
  • 5,787
  • 1
  • 39
  • 40
  • Maybe you got lucky. – Scott Hunter Sep 14 '17 at 01:45
  • 2
    What you're doing results in undefined behavior, which means that all bets are off as to what can happen. The fact that you're only seeing the last value corrupted probably has to do with how the memory allocator works internally. – templatetypedef Sep 14 '17 at 01:47
  • Remove `delete [] arr;` and it will work. You shouldn't delete and then use the variable – Ryan Sep 14 '17 at 01:49
  • You were definitely lucky. It could have happened that the memory was still intact after the `delete` and you wouldn't event notice the error. – Isac Sep 14 '17 at 01:54

2 Answers2

-3

The result you ended up with is totally implementation dependant... I just ran in on MSVC 2015 and got a bunch of random negative and positive numbers outside the range of the generated sequence.

norlesh
  • 1,749
  • 11
  • 23
-3

As Ryan suggested, you allocated memory for an array in main. During populate(), you are deleting that array after populating the array provided by main. You should not delete that array. Array is passed by value but passed by reference. In function populate(), you are not having a copy of array that you can delete. It is the actual array created in main.