Search code examples
c#liststack-overflow

Add an object list to itself?


I was wondering what would happen if I added a list to itself. Maybe a stack overflow, maybe a compiler error?

List<object> lstobj = new List<object>();
lstobj.Add(lstobj);

So I executed the code and checked the local variables:

Local Variables

The list seems to contain an infinite number of list instances. Why is there no stack overflow? Are the lists just pointers to the original list? But even if the lists are just pointers, do pointers not also occupy memory too?


Solution

  • The definition is like this:

    Line 1) object[] arr = new object[4];
    Line 2) arr[0] = arr;
    

    arr[0] is now another alias for arr and both of arr and arr[0] have same value that is address of array data.

    Memory status may be for example as follow:

    After Line 1:

    Address Value
    @100:   104    // arr variable
    @104:   0      // cell[0] of array data
    @108:   0      // cell[1] of array data
    @112:   0      // cell[2] of array data
    @116:   0      // cell[3] of array data
    

    After Line 2:

    Address Value
    @100:   104    // arr variable
    @104:   104    // cell[0] of array data
    @108:   0      // cell[1] of array data
    @112:   0      // cell[2] of array data
    @116:   0      // cell[3] of array data