user1672097
user1672097

Reputation: 351

Memory allocation of members of class

I have class as following:

public class A
{
   int i;
 }

When I am creating and object of class as following:

 A obj=new A();

I can understand the object is allocated in Heap. Now the class got a integer variable. Where the member variable "i" is allocated (in stack or heap)?

Upvotes: 0

Views: 88

Answers (3)

Bhavin Umaraniya
Bhavin Umaraniya

Reputation: 1

All class member will go in heap with continues memory allocation. All variables in a method (local variables) are allocated on stack.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503280

Where the member variable "i" is allocated (in stack or heap)?

It's on the heap - it's part of the memory of the object. (If the variables didn't end up as part of the data of the object, what would you expect the object's data to consist of?)

Of course, as Eric Lippert would point out, the stack is an implementation detail (part one; [part two][2]). Normally you shouldn't worry too much about it. In practice, there have been more and more cases where local variables have started being allocated on the heap:

  • Iterator blocks
  • Captured variables for anonymous functions
  • Asynchronous methods

I haven't seen much evidence of the reverse being true, although it might be possible for a future CLR to use escape analysis to prove that a particular object never had to be allocated on the heap, and allocate it on the stack instead. (I believe some JVMs do this.)

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064004

i is a field, so it is part of the instance itself. Since the instance is on the heap, and is composed of i ... thus i is on the heap.

This becomes more interesting for struct types, as the instance (the value) can be just about anywhere, thus i can be just about anywhere. All you can say is "inside the instance".

Upvotes: 1

Related Questions