0

Say I've got an array that contains 100 elements. Same array only has elements 0 through 69 filled because that's all the data that was captured and 70 through 99 are zeros.

Before the data in the array is transferred, a start of message must be added to the beginning and has to be inserted after gathering the data.

To insert the data, you use a for loop to manually shift the array elements to the right by n (see the code below).

uint8_t foo[100]; 

/*
 * Some code that puts data in the first 70 elements
 */ 

//Need to insert the start of message
for(i=99; i>0; i--)
{
    foo[i+1] = foo[i];
}

On the first run of that for loop, it makes foo[100] = foo[99]. Is that a valid operation or does foo[100] just go off into never never land? I know in languages like MATLAB, it will dynamically resize your array, but does C do the same thing?

Billy
  • 3
  • 4
  • C does not. ```foo[100]``` will go outside the buffer. – Michael Bianconi Aug 14 '19 at 16:02
  • 1
    `foo[100]` is not a valid element of `foo`. It doesn't even go to "never never land", it may modify other variables, cause your program to crash, or introduce any behaviour. This is undefined behaviour. (See [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html).) – Thomas Jager Aug 14 '19 at 16:04
  • You can't assume that elements 70-99 are zeros unless you explicitly assign them – jmq Aug 14 '19 at 16:08
  • Oh my god, Matlab users trying to code (looks familiar to what I see at work). How inefficient to shift everything .. why not keep a header part free, or use a separate header before switching to the array? – kesselhaus Aug 15 '19 at 02:42

1 Answers1

0

C has no bounds checking and it doesn't automatically resize arrays. If you have a size 100 array, and you access index 100 (since arrays start at 0), then you're accessing the memory immediately outside the array's buffer.

Best case scenario, it seg faults. However, since the behavior is undefined, you may be overwriting other variables or doing all kinds of weird stuff.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25