Click here to Skip to main content
15,881,689 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
please explain the memory mapping concept of c# with example.

class A{
int x;
int y;
}

now if i create the object of A class then total memory of class is
A a1=new A();

int x.....contain 4 byte
int y.....contain 4 byte
total 8 byte

a1 always contain extra memory 4 byte

now total memory consumption is 12 byte?

so finally my question is why a1(object of A class) contain 4 byte extra memory while only 2 variable declare in A Class?

can you please explain the memory consumption concept of C# Code with example
Posted
Updated 16-Feb-15 23:39pm
v2
Comments
[no name] 4-Apr-14 0:57am    
You may wish to rephrase your question. Suggest you read this http://www.codeproject.com/Questions/177604/Size-of-a-class-in-c
Sergey Alexandrovich Kryukov 4-Apr-14 1:23am    
The question is clear enough; I basically answered.

Still, the question is not very appropriate. I suggest OP creates some code samples and ask some questions on the observed size in different instruction-set architecture.

—SA
Sergey Alexandrovich Kryukov 4-Apr-14 2:00am    
Not always. This is simply not true.
—SA

1 solution

This is related to word alignment. Memory allocated by the structure/class members may be not continuously aligned, but aligned by some chunks, say, of 32-bit. You can control this alignment using attributes (see the links below), by if you don't, the default is used.

The difference between 64-bit and 32-bit default layout is harder to explain, but the reason is pretty obvious. The thing is: all the types use the same sizes in both kinds of architectures, except the size of the managed pointer: it is 64 or 32 bits, respectively. Therefore, structures or classes having reverence-type instance fields are aligned differently.

Please see:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute.aspx[^].

Please, find out the samples adding 4 or 8 extra bytes to the size of a data type by yourself. If you fail to do this exercise, show what have you tried and what were the results. Then we will be able to discuss it.

—SA
 
Share this answer
 
v2
Comments
[no name] 4-Apr-14 1:32am    
I'm not sure op refers to alignment. If so it does not "always" occur.
Sergey Alexandrovich Kryukov 4-Apr-14 1:58am    
Sigh... No, OP does not refer to alignment, maybe is not even aware of it. The effect observed is related to memory layout, including some word alignment.

OP says "always"? Right. Well, this "always" is a total absurd. Thank you for the great point, I'll comment on that.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900