aelsheikh
aelsheikh

Reputation: 2328

Heap Memory Management .Net

When creating 2 objects of the same type, will the handle from the stack memory point to the same object in the heap or will it point to 2 separate objects. For clarity here is the specific question...

class Q2 {
   private static int num = 0;
   private String prefix;

   public Q2 (String p)
    { prefix = p; }

   public String Msg (String str) {
      String n;
      num++;   
      n = num.ToString();
     return n + " - " + prefix + str;
   }
}

Using an appropriate diagram, describe the state of memory after all of the following statements have been executed.

 Q2 var1, var2;
   var1 = new Q2("Question 2");
   var2 = new Q2 ("Another view");

Here are the answers I cannot decide between:

1 object:

enter image description here

2 objects:

enter image description here

Upvotes: 6

Views: 3552

Answers (4)

Dave Black
Dave Black

Reputation: 8049

To help clarify the discussion on the heaps here, there are about 8 different heaps that the CLR uses:

  1. Loader Heap: contains CLR structures and the type system
  2. High Frequency Heap: statics, MethodTables, FieldDescs, interface map
  3. Low Frequency Heap: EEClass, ClassLoader and lookup tables
  4. Stub Heap: stubs for CAS, COM wrappers, P/Invoke
  5. Large Object Heap: memory allocations that require more than 85k bytes
  6. GC Heap: user allocated heap memory private to the app
  7. JIT Code Heap: memory allocated by mscoreee (Execution Engine) and the JIT compiler for managed code
  8. Process/Base Heap: interop/unmanaged allocations, native memory, etc

HTH

Upvotes: 4

TehBoyan
TehBoyan

Reputation: 6890

You are using the new keyword to instantiate objects in two separate variables, so, this always creates new object on the heap. So the answer would be that it will always point to two separate objects.

EDIT: Static variables such as num are stored in a special area on the heap called High Frequency Heap, that is not being collected by the garbage collector etc.

Upvotes: 3

Rich Turner
Rich Turner

Reputation: 11014

From MSDN:

Only one copy of a static member exists, regardless of how many instances of the class are created.

So, because your class is non-static, you will end up with multiple instances of your class, but they will refer to the same, single, shared, static member instance.

Note: You should be VERY careful with code like the above because you can end up with multiple class instances altering the value of the shared static member which can result in unforeseen behavior, race conditions, corruptions, etc.

If your intent is for the class to be a shared singleton, then mark the class itself as static so that you only ever have one in your heap at any one time.

Upvotes: 2

SLaks
SLaks

Reputation: 888077

.Net will never automatically combine similar objects.

Upvotes: 1

Related Questions