I am working on microntroller RZA1, with KPIT GNUARM 16 toolchain, in e2 studio. I am not an expert on the subject, so I'll try to explain the problem the best that I can. The issue is related to a structure mainwindow
, defined in my code, which contains important features of the graphical interface:
typedef struct
{
page_t pages[MAXNUMPAGE];
logger_t storico;
messagges_t messaggio;
graph_t grafico;
} mainwindow_t;
In the main()
function I declare a local
instance of this struct, as it contains a while(1)
loop, which is used to refresh the GUI application in case of user interaction (i.e pushbutton clicked). The problem that I have encountered is that there's a difference in the way program executes in case the instance of mainwindow_t
is declared with or without static
keyword. For instance,
main()
{
static mainwindow_t mainwindow;
....
init_pages(mainwindow.pages);
while(1)
{
page_update(mainwindow.pages);
}
}
works perfectly well, whereas with only mainwindow_t mainwindow;
it seems that the changes made in the function init_pages() had no effect: entire content of the array page[MAXNUMPAGE] is uninitialized.
Therefore, my question is: should there be any functional difference between non-static local and static local declaration of an array inside a function, if that function basically never returns ?
The problem has nothing to do with whether the variable lives on the stack or not. It has to do with initialization.
Variables with static storage duration, i.e. file-scope variables or local variables with the static
keyword, are implicitly initialized so that (loosely speaking) all variables with arithmetic type are initialized to 0 and all pointer variables are initialized to NULL
.
In contrast, variables with automatic storage duration, i.e. variables declared inside of a function, are not initialized if there is no explicit initializer and its value is indeterminate.
While you didn't show your initialization function, it apparently doesn't set all fields in mainwindow.pages
and depends on the other fields being zero-initialized. When mainwindow
is declared non-static, this results in your program reading some indeterminate fields which causes undefined behavior, which explains why the problem mysteriously disappears when you attempt to trim down the code.
Adding an initializer to mainwindow
addresses this issue by setting any fields explicitly listed, while applying the static object initialization rules to any remaining fields not explicitly initialized.