Search code examples
javacompiler-constructionjvmjasmin

NullPointerException in code created with jasmin bytecode assembler


This code is throwing a java.lang.NullPointerException. I am attempting to compile a bit of code to the jvm and this is what my compiler outputs

.class  public  test
.super  java/lang/Object
.field static   i  [I
.method  public static  main([Ljava/lang/String;)V
invokestatic    test/main()V
return
.limit  locals  1
.limit  stack  20
.end    method
.method  public static  main()V
.limit  locals  8
getstatic   test/i  [I
ldc 1
ldc 5
iastore
return
.limit  stack  20
.end    method

However it is not working an I can figure out where the error is coming from (no line number is given.)

I'm betting it is not storing the value from the global array correctly in the lines

getstatic   test/i  [I
ldc 1
ldc 5
iastore

My question is how should this compile


Solution

  • This will compile to the Java code

    public class Test {
        static int[] i;
        public static void main(String[] args) {
            main();
        }
        public static void main() {
            i[1] = 5;
        }
    }
    

    If you compile and run this, you'll see that it throws a NullPOinterException because nothing is creating an int array to store in i. You need to create an int[] object of dimension 2 (at least) using newarray to make this code work.