Null Pointer Access

New to FreeBASIC? Post your questions here.
Post Reply
nimdays
Posts: 236
Joined: May 29, 2014 22:01
Location: West Java, Indonesia

Null Pointer Access

Post by nimdays »

I dont understand why this causes null pointer

Code: Select all

function update_file(s as string,d as string)as integer
    on error goto hell
    dim as integer ff = freefile, ff1
    dim as string ln
    if open (s for input as #ff) then return 0
    ff1 = freefile
    if open (d for output as #ff1) then
        close #ff : return 0
    end if
         while not eof(ff)
             line input #ff,ln
             if ln[0] = asc("[") then
                 ''
             else
                put #ff1,,ln + !"\n"
             end if
         wend
    close #ff1
    close #ff
    
    return 1
    
    hell:
      ?err
      sleep : end
end function

?update_file("build.txt","build.gradle")

sleep
build.txt

Code: Select all

apply plugin: 'com.android.application'

android {
[0]
	buildToolsVersion "28.0.3"
    defaultConfig {
[1]
[2]
[3]
[4]
[5]
        
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

}
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Null Pointer Access

Post by fxm »

For example, the second line of 'build.txt' is empty, so the corresponding 'ln' is empty (no data characters => Strptr(ln) = 0).
(you can not access a character of an empty string 's' with 's[n]')
You must add a test on the empty lines.
For example;

Code: Select all

        .....
        while not eof(ff)
            line input #ff,ln
            print "'" & ln & "'"
            if ln <> "" then
                if ln[0] = asc("[") then
                    ''
                else
                    put #ff1,,ln + !"\n"
                end if
            end if
        wend
        .....
Explanation (from an example) about the Operator [] (String Index) functioning under the hood::

Code: Select all

Dim As String s = "FreeBASIC"
Dim As Ubyte u
Dim As Uinteger n = 0

u = Strptr(s)[n]  '' equivalent to 'u = s[n]' under the hood
                  '' (closest to the one under the hood should be: 'u = Cptr(Ubyte Ptr, Strptr(s))[n]')
Print Chr(u)

Sleep
Last edited by fxm on Sep 19, 2020 8:22, edited 1 time in total.
nimdays
Posts: 236
Joined: May 29, 2014 22:01
Location: West Java, Indonesia

Re: Null Pointer Access

Post by nimdays »

@fxm, Thank you
Post Reply