verilogsystem-verilog

Output *E,TRNULLID: NULL pointer dereference


class tx;
  pkt p;
  int j;
  function new ( pkt p);
    p = new();
    j =10;
  endfunction
  task copy(pkt p);
    this.p = new p;
  endtask
endclass :tx

initial
  begin  
  tx t1,t2;
  pkt p;

  t1 =new();
  p = new();

  p.i=256;

  t2= new t1;
  t2.j=20;
  t2.copy(p);

  $display(t1.j);
  $display(t2.j);
  $display(p.i);
  $display(t1.p.i);
  $display(t2.p.i);

  t1.p.i=221;
  $display(t1.p.i);
  $display(t2.p.i);
 end
 endprogram

Why this code is not giving output? When I change t1 = new (p), it works fine but give error for few lines:

ncsim> run 10 20 256 ncsim: *E,TRNULLID: NULL pointer dereference.

While it doesn't print for:

   $display(t1.p.i);
   $display(t2.p.i);

Solution

  • Null pointer errors occurs when trying to access a object that doesn't exist.

    For the case of t1 = new(), there should be an warning in the compile/elaboration log. Something along the lines of missing input p. Changing t1 = new() to t1 = new(p) may appear to change resolve the error on that line, but t1.p is still null. This is because input variable has the same name of the as a member variable. When you newed the p inside tx's new it used the input variable because it was closer in scope. Since you assigned a new object to a input handle, the original handle is not pointing to the same object. It would be pointing the the same object if you used you defined the directionality as inout or ref instead as an inferred input. Still the member p would be null.

    Solutions:

    1. Change tx's function new ( pkt p); to function new ();. The input p doesn't appear to be doing anything so there is no reason to have it. p = new() will be assigned to tx's member variable since there is no name conflict.
    2. Change p = new() to this.p = new() in tx's new method. This makes it explicit that the new will apply to the member variable, not the local.
    3. Do both solutions 1 and 2.
    4. If you need both ps and you do not want to do the above, then rename one and use accordingly.