Author: Stan Eisenstat
Subject: Re: [Cs223] Initializing an array
Date: Wednesday, 12 Feb 2020, 08:07:33
> Message Posted By: Unknown > > In my code , I am declaring a new array without assigning any of its > values. The next line declares another variable, totally unrelated to the > array. In gdb, when I go through my code line-by-line, displaying the > array at every line, at the line where I declare the array gdb says the > value of my array = "error cannot access memory at address 0x0." I hit n > once, and at the next line the value of my array has been initialized to > all zeroes except the first element, which is 2. How is it possible for an > array to be initialized to a nonzero value without my having assigned it > any value? The C run-time system allocates storage for every automatic local variable (including an array) on the stack. If there is no explicit initializer, then the initial value(s) of the variable are whatever happens to be in the corresponding location on the stack. But as I conjectured in class, when the length of an array is not known at compile-time, the array variable is replaced by an unitialized pointer variable. When the declaration is "executed", a block of the required size is allocated on the stack and the variable set to its address. In the case above, the initial content of the pointer variable happened to be 0, whence the error from gdb. After the declaration was "executed" and the block of storage allocated, the contents of that block happened to be {2,0,...,0}, so you saw a block of 0's except for the first element. Note that the values might have been different if the previous flow of execution had left different values on the stack. Nice question. --Stan-PREV INDEX NEXT