While writing some code for an AVR Micro-controller, my code would compile but would crash on run time (When I ran the code on the Micro-controller, the Micro-controller would stop functioning) After doing some troubleshooting, I realized I incorrectly initializing a multi-dimensional array.
My question is about how memory for an array is allocated, and is it possible that since there should be data in that memory location and there is not, would this cause the crash?
Suppose I have a 2-dimensional array. Normally, if initialized correctly if could look something like this:
char *monthsDays[12][2] = {
{"Jan", "31" },
{"Feb", "28" },
{"Mar", "31" },
{"Apr", "30" },
{"May", "31" },
{"Jun", "30" },
{"Jul", "31" },
{"Aug", "31" },
{"Sep", "30" },
{"Oct", "31" },
{"Nov", "30" },
{"Dec", "31" }
};
And say I created it like so:
char *monthsDays[12][2] = {
{"Jan", "31" },
{"Feb", "28" }
};
So I have allocated a lot of memory but haven't used it. At run time, is it possible for the unused portion of memory allocated for my array to be used by another part of the program, which in turn cause the crash?
1 Answer 1
When you initialize your array using:
char *monthsDays[12][2] = {
{"Jan", "31" },
{"Feb", "28" }
};
monthsDays[2][0] through monthsDays[11][1] are initialized to 0. Dereferencing them will cause UB. Whether the problem is caused by dereferencing these NULL pointers or some other code stepping on these memory, only you can tell that by looking at the rest of your code.
NULLbut not zero-terminators