SystemVerilog OOP Mastery · All levels

Object Lifetime and Null Handles: Code Examples

Code Examples for Object Lifetime and Null Handles.

Code examples

Conditional construction causes late null dereference

systemverilog
class pkt;\n  rand bit [31:0] addr;\n  function void post_randomize();\n    $display("pkt addr=%08h", addr);\n  endfunction\nendclass\n\ntask build_pkt(bit enable_pkt);\n  pkt p;\n  // BUG: p is only allocated in one branch.\n  if (enable_pkt)\n    p = new();\n  p.post_randomize();\nendtask\n\ntask build_pkt_fix(bit enable_pkt);\n  pkt p = new();\n  // FIX: deterministic allocation plus explicit optional behavior.\n  if (!enable_pkt)\n    return;\n  p.post_randomize();\nendtask

Bug appears only when enable_pkt is false. The fix guarantees lifetime first, then branches on behavior, not existence.

Factory fallback forgotten in error path

systemverilog
class req_base;\n  virtual function string kind();\n    return "base";\n  endfunction\nendclass\n\nclass req_ext extends req_base;\n  function string kind();\n    return "ext";\n  endfunction\nendclass\n\nfunction req_base make_req(bit use_ext);\n  req_base r;\n  // BUG: no else branch, r can remain null.\n  if (use_ext)\n    r = new req_ext();\n  return r;\nendfunction\n\nfunction req_base make_req_fix(bit use_ext);\n  req_base r = new req_base();\n  // FIX: always return a valid object; specialize only when needed.\n  if (use_ext)\n    r = new req_ext();\n  return r;\nendfunction

The crash often appears far from make_req(). A default allocation or explicit null contract avoids hidden lifetime holes.

Related topics