0

I decleared free block like

private DoublyLinkedList freeblock = new DoublyLinkedList();

and I initialize the freeblock in the constructor.

freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize));

inside of one of method of my class, (below is part of my method.) I get null pointer exception. I think the while loop has a problem. Can anyone help me to solve this problem?

symptom: java.lang.NullPointerException at LinearMemPool.enlarge(LinearMemPool.java:220)

private void enlarge(int addSize) {

DoublyLinkedList.Node node = freeblock.head;
    while (node.next != null) { 
            node = node.next;

    }
} 
7
  • 5
    This is a good opportunity to learn how to debug. Commented Sep 16, 2014 at 17:39
  • 1
    If you still want help, best to post a self-contained compilable example. Also, we should know what DoublyLinkedList is all about. Do you have API docs to refer to? The example should match the compiler output so we can see where line "220" actually is in the code. Commented Sep 16, 2014 at 17:41
  • the only thing here that can even possibly throw a nullpointerexception is the "node.next != null" line, because the node variable itself can be null Commented Sep 16, 2014 at 17:42
  • 1
    also what line is line 220? Commented Sep 16, 2014 at 17:43
  • Did you do like a system.out.println(freeblock.head) to see if it null or not? Commented Sep 16, 2014 at 17:43

3 Answers 3

1

Evidently freeblock.head is null. Look what add does.

Sign up to request clarification or add additional context in comments.

Comments

0

Your enlarge method seems a bit dangerous. Try changing the null check to:

private void enlarge(int addSize) {
    DoublyLinkedList.Node node = freeblock.head;
    while (node != null) { 
        node = node.next;
    }
}

As for the reason why your head is null, I'd debug the freeblock.add(...) method.

3 Comments

I suggest to simplify it then DoublyLinkedList.Node node = null;
@talex DoublyLinkedList.Node node = freeblock.head; is fine. OP needs a starting node.
I mean as result in you code you get node==null. Original code get node equal to last node in list.
0

First check to see freeblock.head is null because most likely it is:

if(node!=null){

   while(node.next!=null){
   ....
}

else{
 System.out.println("Freeblock is null but why.....");

}

You probably should do this normally if the freeblock.head can ever be null. And just for cleaning up purposes:

void newMethod(Node node, int size){
 if(node!=null)
   enlarge(size);
 else{
   System.out.println("Freeblock is null");
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.