0

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?

asked Feb 4, 2015 at 17:02
5
  • no. not without some other bug in your code that we cant see Commented Feb 4, 2015 at 17:07
  • the rest of the array is zero-initialized. So there should be no problems, unless in your specific case you access that area expecting a null-terminating string. Commented Feb 4, 2015 at 17:08
  • Ok, I'll have to do more troubleshooting. Its hard to re-create outside of the Micro-Controller environment. Commented Feb 4, 2015 at 17:10
  • @bolov it is an array of pointers (to string literals where declared), the undefined ones containing NULL but not zero-terminators Commented Feb 4, 2015 at 17:11
  • @WeatherVane that was my point Commented Feb 4, 2015 at 17:43

1 Answer 1

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.

answered Feb 4, 2015 at 17:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.