2

I have dynamically allocated memory for an array of 5 elements, then tried to print its elements to std::cout, which should have left me with a fairly straightforward result. I got something else instead, and it left me with some questions.

My code:

#include <iostream>

int main()
{
    int *array = new int[5];

    int array_size = sizeof(array);
    for (int index = 0; index < array_size; index++) {
        std::cout << array[index] << "\n";
    }
    std::cout << "\nThe array is " << array_size << " elements long.";

    return 0;
}

This is what this resulted in:

0
0
0
0
0
0
132049
0

Now, I understand this isn't how things are done, but such a result has left me with several questions.

  1. Why is the size of the array 8, and not 5? Originally, I thought that it's becase the memory according to powers of 2, but I have a feeling I'm wrong.
  2. What's with 132049?
Ivan T.
  • 525
  • 5
  • 19

1 Answers1

4

Your code has two problems, each of them leading to undefined behavior.

First, sizeof(array) is the size of the pointer in bytes, not the array. On your machine, a pointer happens to take 8 bytes. This causes out-of-range access, which is undefined behavior.

Second, new int[5] gives you an uninitialized array. Accessing the value of an uninitialized object is undefined behavior.

To fix these problems, first note that the size of an array returned by new is lost. sizeof cannot help you. You can only provide this information yourself. Then you have to initialize the elements.

#include <iostream>

int main()
{
    int *array = new int[5]{}; // note: initialization

    int array_size = 5;
    for (int index = 0; index < array_size; index++) {
        std::cout << array[index] << "\n";
    }
    std::cout << "\nThe array is " << array_size << " elements long.";

    return 0;
}

This is code is guaranteed to print

0
0
0
0
0

The array is 5 elements long.

(As long as there is enough memory and output succeeds)

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • My assumption, then, would be that allocation and initialization are different procedures? I mean, it seems kinda obvious if you think about it - one is reserving a spot, the other is filling it. – Ivan T. Jul 10 '19 at 07:38
  • 1
    @IvanT. `new` default-initializes, but default-initialization on a `int` doesn't actually initialize it. Just like `int x;`. – L. F. Jul 10 '19 at 07:39
  • @IvanT. You may be interested in the answers to [How to initialise memory with new operator in C++?](https://stackoverflow.com/questions/2204176/how-to-initialise-memory-with-new-operator-in-c). – pandorafalters Jul 10 '19 at 07:49