Object deallocation in sv

Hello Readers

Suppose I have created 10 objects by using new() constructor of classes.

Ex:-
class A;

endclass

class B

endclass

initial begin
A a=new();
B b=new();
end

I am also keeping a track of a number of objects created by incrementing the no_obj_ctreate++.

now, I want to deallocate memory of 2 created object manually by using “null”.

how to count the total number of the object remaining.

please tell the logic or code to write in a function.

In reply to Pradyumna Panda:

This seems like a really good interview question. I’ll give you a hint that it’s a trick question.

In reply to dave_59:

Thanks, Dave.

Well, I have tried some code out by having failed, I have no way out. My approach was to declare a function in which I was deallocating memory by assigning null and the Decreasing the no_obj_ctreate.

When I called the function , it didn’t work.

In reply to Pradyumna Panda:

Hi Pradyumna I liked the question and thought that the approach could be something like this. Do let me know your thoughts:


module mod();

class base1;
//body of the class
endclass

class base2;
//body of the class
endclass

base1 child1[];
base2 child2[];
int null_obj1;
int null_obj2;

initial begin
child1=new[10];
child2=new[5];

//Creating Objects
foreach (child1[i])
child1[i]=new();

foreach (child2[i])
child2[i]=new();

//Deallocating Objects
child2[3]=null;
child1[4]=null;

//Finding Null Objects Count
null_obj1=child1.sum with (int'(item==null));
null_obj2=child2.sum with (int'(item==null));

$display("-------------------");
$display("Null objects of Class Base1:%d",null_obj1);
$display("Null objects of Class Base2;%d",null_obj2);
endmodule

In reply to Pradyumna Panda:

You are correct, there is no way to do this in SystemVerilog. Assigning null to a class variable does not necessarily deallocate the object it had a handle to.

In reply to dave_59:

Hi Dave, if assigning null to class object handle “don’t deallocate the object” then what actually it does, object exist with no value or no memory, just handle, is that what you are trying to say?

In reply to megamind:

In reply to dave_59:
Hi Dave, if assigning null to class object handle “don’t deallocate the object” then what actually it does, object exist with no value or no memory, just handle, is that what you are trying to say?

SystemVerilog is using “garbage collection” mechanism to manage object deallocation.
Alternatively, user does not need to de-allocate object manually, SV will do it automatically when there are no references to the object.

Then, assign null to object does not mean it will be de-allocated.