Home > OS >  Why does the order of array declaration matter in an embedded system?
Why does the order of array declaration matter in an embedded system?

Time:10-02

I'm writing some code for a class and I need to manipulate some user input. The input is a user string that contains a hex value for a memory address and a word/phrase up to 16 characters long. Each character after the memory address is then converted to a hex value and that value is then used to set the byte value at the memory address specified.

  Cmd *new_cp = &cmds[1];
  int memAddrs_int = 0;
  char userString [16] = "";
  char memAddrs_str [16] = "";
  char argsToPass [16] = "";
  char byteValue [2] = "";

This code copiles and runs just fine on a linux environment but when I run it in a VM that simulates an embedded system, I get a page fault exception. While renaming some variables I changed the order of the arrays to:

Cmd *new_cp = &cmds[1];
int memAddrs_int = 0;
char userString [16] = "";
char argsToPass [16] = "";
char memAddrs_str [16] = "";
char byteValue [2] = "";

and now everything works as expected. Any ideas as to why the order that the arrays were declared and initialized would matter on an embedded system? Or would this have something to do with the fact that it is running on a VM?

CodePudding user response:

It is not the order of declaration that is causal here. Rather some memory access error elsewhere having a different effect because the declaration order affects what adjacent data object is being corrupted and later accessed and used.

Somewhere in your code you have a bug with "undefined behaviour" results, and any change, including declaration order of unrelated data objects can affect actual behaviour. The behaviour could even change spontaneously with no changes.

CodePudding user response:

You have

char byteValue [2] = "";

If the byteValue array is intended to hold strings like "3d" (as you confirmed in a comment that it is), then it needs to be declared with three elements, including one for the necessary null terminator:

char byteValue [3] = "";

When it was declared with a size of 2, and when some code wrote three bytes there and overflowed it, some other piece of memory got overwritten. We don't know what piece of memory that was, or what the effect was — benign or catastrophic or somewhere in between — but it's not too surprising that changing the order of the declarations changed the circumstances.

  • Related