Associative array not able to populate correct value

I have a class which i want to store in associative array. Once i store it i dont see the correct value when i populate it back.



module tb;
  class abc;
    rand bit [31:0] addr;
    endclass
  
  abc acc[int];
  
  initial begin
    
    
    for (int i=0; i<5;i++)
      begin
        //#1
        abc a=new();
        if (!a.randomize()) begin
          $display ("Error");
        end
        $display ("Addr is %h",a.addr);
        acc[i] = a;
       // #1;
      end
    $display ("Addr is %h",acc[1].addr);
  end
  
endmodule

Output :
Addr is 18638aa3
Addr is aab747d6
Addr is 5dea6c01
Addr is 1b7882c9
Addr is 06cf862d
Addr is 06cf862d

Expected output:
Addr is 18638aa3
Addr is aab747d6
Addr is 5dea6c01
Addr is 1b7882c9
Addr is 06cf862d
Addr is aab747d6

In reply to rag123:

The code you wrote is illegal and should have been caught as error for the very reason you do not see the problem here. See Local var assignment in static function | Verification Academy

In reply to dave_59:

In reply to rag123:
The code you wrote is illegal and should have been caught as error for the very reason you do not see the problem here. See Local var assignment in static function - SystemVerilog - Verification Academy

Hi Dave,
what is the best way to fix this?

In reply to rag123:


module tb;
  class abc;
    rand bit [31:0] addr;
    endclass
 
  abc acc[int];
 
  initial begin
 
 
    for (int i=0; i<5;i++)
      begin
        //#1
        //abc a=new(); //ISSUE: this line execution happen only once, so you have only one instance/handle which you are modifying in each iteration and acc all element point to the same handle 
        abc a;
        //FIX : create new handle in each iteration
        a =new();
        if (!a.randomize()) begin
          $display ("Error");
        end
        $display ("Addr is %h",a.addr);
        acc[i] = a;
       // #1;
      end
    $display ("Addr is %h",acc[1].addr);
  end
 
endmodule

In reply to Rahulkumar:

Strongly suggest that you not declare implicitly static variables inside looping code. Even better is keeping static variable declarations outside of procedural blocks.