PDA

View Full Version : Array data being corrupted



caverman
- 17th March 2006, 03:13
If I use the following:
TR var word[7] 'trim
G var byte[7] 'gain
R var bit[7] 'reverse
C var byte[7] 'center
AD var bit[7] '0=Ana, 1=Digital
LM var byte[7] 'left max measured from 0. Is <RM
RM var byte[7] 'right max measured from 0. Is >LM
'hard coded S5 var byte[8] 'Channel 5, 8 states 0->255, gets *4 for uS
'hard coded S6 var byte[8] 'Channel 6, 8 states 0->255, gets *4 for uS
DB var byte[7] 'deadband around center value -> no servo change
arrayPVal var word[7]

I find that TR[0] gets strange (corrupted) data in it TR[1] data is OK
TR[0] also get zonked if I move its line to the end after arrayPVal.

Now if I use
TR var word[8] 'trim
G var byte[8] 'gain
R var bit[8] 'reverse
C var byte[8] 'center
AD var bit[8] '0=Ana, 1=Digital
LM var byte[8] 'left max measured from 0. Is <RM
RM var byte[8] 'right max measured from 0. Is >LM
'hard coded S5 var byte[8] 'Channel 5, 8 states 0->255, gets *4 for uS
'hard coded S6 var byte[8] 'Channel 6, 8 states 0->255, gets *4 for uS
DB var byte[8] 'deadband around center value -> no servo change
arrayPVal var word[8]

it all seems to work OK

Any thoughts on why. Sure words and things need to be alinged in memory
but I would have though PICBasic Pro would have sorted that out for me.

Thanks

Bruce
- 17th March 2006, 04:22
If you compile nothing but your variables, you'll see that PBP creates arrayPVal var word[7] first, followed immediately by TR var word[7].

If your code does something like arrayPVal[7] = 10, then you're writing outside the bounds of your array arrayPVal, and accessing TR[0].

PBP does not perform bounds checking when accessing arrays.

arrayPVal var word[7] ' = arrayPVal[0] to arrayPVal[6]
TR var word[7] ' = TR[0] to TR[6]

With PBP allocating RAM for arrayPVal followed immediately by TR, then arrayPVal[7] = 0 will actually clear TR[0]. You will not get an error at compile time, but you will not be working on the array element you think you are.

I.E. you would then be corrupting the low byte in TR[0], which would simulate your problem.