Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my empty array not empty?

Tags:

c++

c

xcode

I write the following code and set a breakpoint in xcode:

#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
    int array[12];
    return 0;        //Set breakpoint here
}

enter image description here

The debugger panel shows the first 6 elements contain non zero ints. Why is this?

like image 855
Matt Harrison Avatar asked Apr 25 '26 17:04

Matt Harrison


2 Answers

int array[12];

This declares an array with 12 elements, not an empty array.

Furthermore it declares them without an initializer, which (in function scope) means that they will be default initialized. For int that means no initialization is performed and the resulting ints will have indeterminate values. This behavior is defined in the specification for C++.

If you want to zero initialize the array then you need to give it an initializer:

int array[12] = {};

The reason that this is not forced behavior is that there is a performance cost to initialization and some programs are written to work correctly without needing to suffer that penalty.

like image 71
bames53 Avatar answered Apr 28 '26 06:04

bames53


Because you only declared the array, not initialized it.

When you declare the only thing that happens is that you reserve a certain area of memory. What is already stored on that area can be anything left over from other operations/programs.

like image 25
paul23 Avatar answered Apr 28 '26 07:04

paul23