Can anyone explain why would some local array elements show random numbers?
A global array is part of the global uninitialised data section (.data? in assembler notation). This area of memory gets zeroed by the OS before handing it over to the executable, so you don't need to zero it yourself.
In contrast, all local variables are set up on entry to a function using a stack frame:
main:
push ebp
mov ebp, esp
sub esp, 3C //create space for 0x3c bytes of local variablesWhen doing so, you get whatever garbage happened to be between the new and old stack pointer.
This seems, by the way, not true for double arrays:
int main (void)
{
double myd[100];This allocates the array in the .data section, at least in my tests with Pelles C.
C apparently does not foresee an option to initialise local variables, see
Visual studio 2005: is there a compiler option to initialize all stack-based variables to zero?Is there a gcc flag to initialise local variable storage? ("certain copies of GCC ... have a -finit-local-zero option")
In Basic, Fortran, Python and many other languages, initialisation is standard. Even in Assembler you can easily write a macro (which uses a library function, one 5 bytes call for all local variables):
MyTest proc arg1:DWORD, arg2:RECT
LOCAL v1, v2, rc:RECT, buffer[100]:BYTE
ClearLocalVariablesThe performance loss of initialisation is negligible, unless you call a function a Million times in an innermost loop (and even initialising 100 bytes of local variables a Million times costs a mere 40 ms, measured on a trusty old Celeron...).
I've tried to implement something similar in Pelles C, but it turns out to be very tricky because the compiler "optimises" the stack frame in various ways. Curious to hear if others have tried this road, too. Perhaps it could be squeezed into the PROLOGUE macro??