Sunday, October 9, 2022

[SOLVED] Why does the order of array declaration matter in an embedded system?

Issue

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?


Solution

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.



Answered By - Steve Summit
Answer Checked By - Cary Denson (WPSolving Admin)