2
#include <iostream>
using namespace std;

int main() {
    bool *a = new bool[10];

    cout << sizeof(bool) << endl;
    cout << sizeof(a[0]) << endl;

    for (int i = 0; i < 10; i++) {
        cout << a[i] << " ";
    }

    delete[] a;
}

The above code outputs:

1
1
112 104 151 0 0 0 0 0 88 1 

The last line should contain garbage values, but why are they not all 0 or 1? The same thing happens for a stack-allocated array.

Solved: I forgot that sizeof counts bytes, not bits as I thought.

Alan
  • 175
  • 4
  • 15

5 Answers5

8

You have an array of default-initialized bools. Default-initialization for primitive types entail no initialization, thus they all have indeterminate values.

You can zero-initialize them by providing a pair of parentheses:

bool *a = new bool[10]();

Booleans are 1-byte integral types so the reason you're seeing this output is probably because that is the data on the stack at that moment that can be viewed with a single byte. Notice how they are values under 255 (the largest number that can be produced from an unsigned 1-byte integer).

OTOH, printing out an indeterminate value is Undefined Behavior, so there really is no logic to consider in this program.

David G
  • 94,763
  • 41
  • 167
  • 253
1

What you are seeing is uninitialized values, different compilers generate different code. On GCC I see everything as 0 on windows i see junk values.

generally char is the smallest byte addressable- even though bool has 1/0 value- memory access wise it will be a char. Thus you will never see junk value greater than 255

Following initialization (memset fixes the things for you)

#include <iostream>
using namespace std;

int main() {
    bool* a = new bool[10];

    memset(a, 0, 10*sizeof(bool));

    cout << sizeof(bool) << endl;
    cout << sizeof(a[0]) << endl;

    for (int i = 0; i < 10; ++i)
    {
        bool b = a[i];
        cout << b << " ";
    }

    return 0;
}
Sarang
  • 1,867
  • 1
  • 16
  • 31
1

Formally speaking, as pointed out in this answer, reading any uninitialized variable is undefined behaviour, which basically means everything is possible.

More practically, the memory used by those bools is filled with what you called garbage. ostreams operator<< inserts booleans via std::num_put::put(), which, if boolalpha is not set, converts the value present to an int and outputs the result.

Community
  • 1
  • 1
Philipp Lenk
  • 921
  • 6
  • 14
1

sizeof(bool) on your machine returns 1.

That's 1 byte, not 1 bit, so the values you show can certainly be present.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
-2

I do not know why you put a * sign before variable a . Is it a pointer to point a top element address of the array?

btrbt
  • 42
  • 3