Associative array not cleared when function is done

I have an associative array which is defined inside a function, but when the function is finished, the associative array is not cleared. When I recall the function, the associative array still have the item from last function call.
Here is the code:

 class A;
  rand int num[10];

  rand int helper[10];
  constraint num_c{
      num[i] inside {[0:9]};
module top;
  initial begin
    A a = new();
    repeat(10) begin
      $display("randomized number: %0p", a.num);

// check the number of unqiue number in a array

function int check_un(int arr[]);
  int hash_arr[int];
  int unique_arr[$];
  int result;
  for(int i=0;i<arr.size();i++) begin
    if(hash_arr.exists(arr[i])) hash_arr[arr[i]]++;
    else hash_arr[arr[i]] = 1;

  unique_arr = hash_arr.find_index() with (item == 1);
  result = unique_arr.size();
  $display("hash arr is %p", hash_arr);
  return result;


Here is the output:
randomized number: '{0, 1, 4, 4, 4, 6, 7, 7, 7, 7}
hash arr is '{0x0:1, 0x1:1, 0x4:3, 0x6:1, 0x7:4}
randomized number: '{1, 9, 3, 9, 2, 9, 2, 1, 9, 2}
hash arr is '{0x0:1, 0x1:3, 0x2:3, 0x3:1, 0x4:3, 0x6:1, 0x7:4, 0x9:4}
randomized number: '{1, 3, 3, 8, 6, 8, 2, 5, 7, 9}
hash arr is '{0x0:1, 0x1:4, 0x2:4, 0x3:3, 0x4:3, 0x5:1, 0x6:2, 0x7:5, 0x8:2, 0x9:5}

edaplayground link: check the number of unique number - EDA Playground

In reply to wyc123:

That is because your function has a static lifetime, and all the variables declared inside the function (as well its arguments and return value) have a implicitly static lifetime as well.

You need to declare the function with an automatic lifetime (preferred), or the individual variables you want. See The life of a SystemVerilog Variable.

In reply to dave_59:

Thank you very much Dave!

Quick follow up question. If I define a function in UVM monitor or driver, do I need to declare it with automatic to have a dynamic life time?

In reply to wyc123:

Hi ,
No, you don’t need to. Because class itself is a dynamic structure. In the given example, had you made the function inside the class, you wouldn’t have had any problems.

In reply to wyc123:

Class methods have only automatic lifetimes. Please the link I gave you to understand the difference between static, automatic, and dynamic lifetimes.