neilsf / XC-BASIC

A compiling BASIC dialect for the Commodore-64
https://xc-basic.net/
MIT License
74 stars 15 forks source link

Possible problem with 2D byte arrays - other byte variable share same address with the array #96

Closed JJFlash-IT closed 4 years ago

JJFlash-IT commented 4 years ago

Hello (and sorry for my English, I'm from Italy)! I think I found a bug regarding the handling of 2D byte(!) arrays: I was porting a little Freebasic demo of mine to XC=BASIC, and I had a really hard time figuring out why the program was crashing and behaving erratically. After some debugging, I saw that some of the byte(!) variables I used were getting overwritten with seemingly random values. Thanks to the @ operator, I think I finally figured it out.

If you try to compile and run this (note: I'm using version 2.2.03 because that's reported as the stable version on the xc-basic site at the moment):

dim Array![2, 6]
Variable1! = 0
Variable2! = 0
Variable3! = 0
Variable4! = 0

IndexX! = 0
IndexY! = 0

for nIndexY! = 0 to 5
    for nIndexX! = 0 to 1
        print nIndexX! ; : print " " ; : print nIndexY! ; : print " " ; : print @Array![nIndexX!, nIndexY!]
    next nIndexX!
next nIndexY!

print @Variable1!
print @Variable2!
print @Variable3!
print @Variable4!

You'll see this as output:

0 0 3127
1 0 3128
0 1 3133
1 1 3134
0 2 3139
1 2 3140
0 3 3145
1 3 3146
0 4 3151
1 4 3152
0 5 3157
1 5 3158
3139
3140
3141
3142

With this, you can see that Variable1! and Variable2! share the same address as the [2,0] and [2,1] elements of Array! ! If you declare the Array last instead of first (after the byte variables, I mean), there will be no conflict of address.

I haven't tested integer and float 2D arrays for the same behaviour.

Incidentally: why that jump of 5 bytes in the array elements? Shouldn't they be contiguous? Probably there's something I'm missing :)

Thanks and keep up the great work! Apart from this problem, I really enjoyed the porting experiment! :D

neilsf commented 4 years ago

Hi Thanks for reporting this issue. I can confirm that there is a bug here. It seems that the addresses of 2 dimensional array members are not correctly resolved. I'll fix this ASAP.

neilsf commented 4 years ago

Fixed now. Please download v2.2.05 from here: https://github.com/neilsf/XC-BASIC/releases/tag/v2.2.05

JJFlash-IT commented 4 years ago

Downloaded! I tried the same program above and now it seems to work perfectly!

0 0 3127
1 0 3128
0 1 3129
1 1 3130
0 2 3131
1 2 3132
0 3 3133
1 3 3134
0 4 3135
1 4 3136
0 5 3137
1 5 3138
3139
3140
3141
3142

I can see now that it only messed up during the 1D index calculation, not during the variable "allocation", hence the overwriting. Thanks again!