BUG? 0 index on an empty string crashes program

General FreeBASIC programming questions.
Post Reply
Neophyte
Posts: 6
Joined: Aug 03, 2005 23:44

BUG? 0 index on an empty string crashes program

Post by Neophyte »

Hello,

Create a new text file with this in it:
a

b
Now use the following code:

Code: Select all

DIM buffer AS STRING

' Find the first free file handle.
f = FREEFILE

OPEN "Source.txt" FOR Input AS #f
  do until Eof(f) = -1
    'Fetch our string from the file.
    Line Input #f, buffer
   
    'Print our string and the first letter of the string
    Print buffer
    Print buffer[0] 'Will crash on second line after "a".
    sleep 'Hit enter to move onto the next line
  loop
 

' Close all open files. 
CLOSE
sleep
END
It will crash after the "a". It appears any time you try to access the first character of an empty string using indicies the compiler will crash. This problem will not occur with zstrings. Only with regular strings. Why is this happening?
mjs
Site Admin
Posts: 842
Joined: Jun 16, 2005 19:50
Location: Germany

Post by mjs »

All strings have a pointer to their data. An empty string has a pointer to NULL. Accessing NULL causes the GPF.

You should really test the string length before you try to access an invalid memory address.

Regards,
Mark
Neophyte
Posts: 6
Joined: Aug 03, 2005 23:44

Post by Neophyte »

Thanks for the advice. I understand what is happening now. :)
Post Reply