SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
SOM-ITSOLUTIONS
C++
Memory layout in C++ vis-a-vis Polymorphism and Padding bits
SOMENATH MUKHOPADHYAY
som-itsolutions
#A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282
Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com
Website: ​www.som-itsolutions.com
Blog:​ www.som-itsolutions.blogspot.com
I know there is no need for the knowledge of memory layout for a normal day-to-day development of C++.
However, when someone goes in the bit/byte level of C++, he needs looks for such discussion.
To state the problem, let us have a class hierarchy like the following.
class​ ​A​ {
​public​:
​virtual​ ​void​ funA()
{}
​virtual​ ​~​A(){}
public​:
​int​ a;
};
class​ ​B​ {
​public​:
​virtual​ ​void​ funB(){};
​virtual​ ​~​B(){}
public​:
​int​ b;
};
class​ ​C​ ​:​ ​public​ A, ​public​ B {
public​:
​int​ c;
};
Now if we run this app using a GCC compiler on a 64 bit machine and see the sizeof() these classes, we will
see A will be 16 byte, B will be 16 byte and C will be of 32 bytes . So lets discuss how these numbers have
come.
To start with the discussion, i need to throw some lights about how polymorphic behavior in C++ using
virtual functions is tackeled by a compiler. Whenever there is a class having virtual function, the compiler will
generate a VTABLE of that class and all the objects of that class will use that VTABLE. VTABLE is nothing
but a TABLE having pointers to the virtual functions in a class hierarchy. And whenever there is a VTABLE,
the compiler will silently add a pointer in the beginning of an object of the class. This pointer is called vptr
and it actually points to the beginning of the VTABLE.
2​ | ​Page
So in the following case two VTABLES will be created (each for class A and B).
Hence the size of an object of class A will be size-of-a-pointer(vptr) + size-of-int. So for a 64 bit architecture
(where a pointer is 8 byte long) it will be 8 + 4 = 12. If this is the case, then how come sizeof(A) shows 16.
Here comes the concept of Alignment and Padding bits.
Here is an excerpt from Wiki about alignment.
"A memory address a, is said to be n-byte aligned when a is a multiple of n bytes (where n is a power of 2).
In this context a byte is the smallest unit of memory access, i.e. each memory address specifies a different
byte. An n-byte aligned address would have log2(n) least-significant zeros when expressed in binary.
The alternate wording b-bit aligned designates a b/8 byte aligned address (ex. 64-bit aligned is 8 bytes
aligned).
A memory access is said to be aligned when the datum being accessed is n bytes long and the datum
address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by
definition byte memory accesses are always aligned.
A memory pointer that refers to primitive data that is n bytes long is said to be aligned if it is only allowed to
contain addresses that are n-byte aligned, otherwise it is said to be unaligned. A memory pointer that refers
to a data aggregate (a data structure or array) is aligned if (and only if) each primitive datum in the
aggregate is aligned.
Note that the definitions above assume that each primitive datum is a power of two bytes long. When this is
not the case (as with 80-bit floating-point on x86) the context influences the conditions where the datum is
considered aligned or not.
Data structures can be stored in memory on the stack with a static size known as bounded or on the heap
with a dynamic size known as unbounded."
To maintain the alignment, compiler inserts padding bits in the compiled code of a structure/class object.
"Although the compiler (or interpreter) normally allocates individual data items on aligned boundaries, data
structures often have members with different alignment requirements. To maintain proper alignment the
translator normally inserts additional unnamed data members so that each member is properly aligned. In
3​ | ​Page
addition the data structure as a whole may be padded with a final unnamed member. This allows each
member of an array of structures to be properly aligned. .... ....
Padding is only inserted when a structure member is followed by a member with a larger alignment
requirement or at the end of the structure" - Wiki
To get more info about how GCC does it, please look at
http://www.delorie.com/gnu/docs/gcc/gccint_111.html
and search for the text "basic-align".
Now lets come to this problem:
Using the example class, i have created this program for a GCC compiler running on a 64 bit Ubuntu.
int​ ​main​() {
A objA;
C objC;
cout​<<​sizeof​(​void​*​)​<<​endl;
cout​<<​sizeof​(​int​)​<<​endl;
cout​<<​sizeof​(A)​<<​endl;
cout​<<​sizeof​(B)​<<​endl;
cout​<<​sizeof​(C)​<<​endl;
​return​ ​0​;
}
And the result for this program is as the following:
8
4
16
16
4​ | ​Page
32
As i was saying that object of class A will have a VPTR (pointing to the VTABLE of A) and an int. The
pointer will be 8 byte long and the int will be 4 byte long. Hence before compile the size is 12 bytes. But the
compiler will add extra 4 bytes at the end of int a as padding bits to maintain the alignment of class A equal
to the highest length of the data member of the class which is divisible by 2, that is vPtr (8 byte long). Hence
after compilation, the A's objects size will be 12 + 4 = 16 bytes.
Similarly for class B's objects.
Now object of C will have two VPTRs (one for each class A & class B) and 3 ints (a,b,c). So normally the
size of object of C should have been 8 + 8 + 3*4 = 28 bytes. But here is what happens because the compiler
adds padding bytes. After the addition of the padding bytes, the size becomes 8 (VPTR A) + 4 (int a) + 4
(padding bytes) + 8 (VPTR B) + 4 (int b) + 4 (int c) = 32 bytes. So the total size of C will be 32 bytes.
Note:
Type this to see the memory dump on the screen using gcc compiler
g++ -fdump-class-hierarchy=stdout MemoryLayout.cpp
where ​MemoryLayout.cpp ​is the file containing the class hierarchy…
5​ | ​Page

Mais conteúdo relacionado

Mais procurados

Computer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletComputer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletPittock
 
250903944 3 homework2010_3
250903944 3 homework2010_3250903944 3 homework2010_3
250903944 3 homework2010_3Jerry Snow
 
IIIRJET-Implementation of Image Compression Algorithm on FPGA
IIIRJET-Implementation of Image Compression Algorithm on FPGAIIIRJET-Implementation of Image Compression Algorithm on FPGA
IIIRJET-Implementation of Image Compression Algorithm on FPGAIRJET Journal
 
Time series predictions using LSTMs
Time series predictions using LSTMsTime series predictions using LSTMs
Time series predictions using LSTMsSetu Chokshi
 
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AES
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AESCFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AES
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AESidescitation
 
Memory mapping techniques and low power memory design
Memory mapping techniques and low power memory designMemory mapping techniques and low power memory design
Memory mapping techniques and low power memory designUET Taxila
 
Discrete lecture 01
Discrete lecture 01Discrete lecture 01
Discrete lecture 01Raja Hamid
 
Devry gsp 215 week 3 homework representing and manipulating information new
Devry gsp 215 week 3 homework representing and manipulating information newDevry gsp 215 week 3 homework representing and manipulating information new
Devry gsp 215 week 3 homework representing and manipulating information newwilliamethan912
 
Cache management
Cache managementCache management
Cache managementUET Taxila
 

Mais procurados (18)

15 Jo P Mar 08
15 Jo P Mar 0815 Jo P Mar 08
15 Jo P Mar 08
 
Computer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletComputer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutlet
 
Chap 13(dynamic memory allocation)
Chap 13(dynamic memory allocation)Chap 13(dynamic memory allocation)
Chap 13(dynamic memory allocation)
 
250903944 3 homework2010_3
250903944 3 homework2010_3250903944 3 homework2010_3
250903944 3 homework2010_3
 
Capp june 2012
Capp june 2012Capp june 2012
Capp june 2012
 
IIIRJET-Implementation of Image Compression Algorithm on FPGA
IIIRJET-Implementation of Image Compression Algorithm on FPGAIIIRJET-Implementation of Image Compression Algorithm on FPGA
IIIRJET-Implementation of Image Compression Algorithm on FPGA
 
Time series predictions using LSTMs
Time series predictions using LSTMsTime series predictions using LSTMs
Time series predictions using LSTMs
 
Data Applied: Clustering
Data Applied: ClusteringData Applied: Clustering
Data Applied: Clustering
 
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AES
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AESCFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AES
CFA based SBOX and Modified Mixcolumn Implementation of 8 Bit Datapath for AES
 
Memory mapping techniques and low power memory design
Memory mapping techniques and low power memory designMemory mapping techniques and low power memory design
Memory mapping techniques and low power memory design
 
Standard libraries
Standard librariesStandard libraries
Standard libraries
 
A03530107
A03530107A03530107
A03530107
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Discrete lecture 01
Discrete lecture 01Discrete lecture 01
Discrete lecture 01
 
Devry gsp 215 week 3 homework representing and manipulating information new
Devry gsp 215 week 3 homework representing and manipulating information newDevry gsp 215 week 3 homework representing and manipulating information new
Devry gsp 215 week 3 homework representing and manipulating information new
 
Data strucer
Data strucerData strucer
Data strucer
 
Cache management
Cache managementCache management
Cache management
 
Oops recap
Oops recapOops recap
Oops recap
 

Semelhante a Memory layout in C++ vis a-vis polymorphism and padding bits

The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryPVS-Studio
 
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryInterview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryPVS-Studio
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
 
Virtual Method Table and accident prevention
Virtual Method Table and accident preventionVirtual Method Table and accident prevention
Virtual Method Table and accident preventionAndrey Karpov
 
Csc4320 chapter 8 2
Csc4320 chapter 8 2Csc4320 chapter 8 2
Csc4320 chapter 8 2bshikhar13
 
Lesson 23. Pattern 15. Growth of structures' sizes
Lesson 23. Pattern 15. Growth of structures' sizesLesson 23. Pattern 15. Growth of structures' sizes
Lesson 23. Pattern 15. Growth of structures' sizesPVS-Studio
 
A nice 64-bit error in C
A  nice 64-bit error in CA  nice 64-bit error in C
A nice 64-bit error in CPVS-Studio
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticPVS-Studio
 
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxPlease do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxARIV4
 
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxtidwellveronique
 
ECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxtidwellveronique
 
ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata EvonCanales257
 
Ashish garg research paper 660_CamReady
Ashish garg research paper 660_CamReadyAshish garg research paper 660_CamReady
Ashish garg research paper 660_CamReadyAshish Garg
 
Static code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xStatic code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xPVS-Studio
 
Static code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xStatic code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xAndrey Karpov
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...apidays
 

Semelhante a Memory layout in C++ vis a-vis polymorphism and padding bits (20)

The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memory
 
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ libraryInterview with Anatoliy Kuznetsov, the author of BitMagic C++ library
Interview with Anatoliy Kuznetsov, the author of BitMagic C++ library
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
06 linked list
06 linked list06 linked list
06 linked list
 
Linked list
Linked listLinked list
Linked list
 
Virtual Method Table and accident prevention
Virtual Method Table and accident preventionVirtual Method Table and accident prevention
Virtual Method Table and accident prevention
 
Csc4320 chapter 8 2
Csc4320 chapter 8 2Csc4320 chapter 8 2
Csc4320 chapter 8 2
 
Lesson 23. Pattern 15. Growth of structures' sizes
Lesson 23. Pattern 15. Growth of structures' sizesLesson 23. Pattern 15. Growth of structures' sizes
Lesson 23. Pattern 15. Growth of structures' sizes
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
A nice 64-bit error in C
A  nice 64-bit error in CA  nice 64-bit error in C
A nice 64-bit error in C
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmetic
 
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxPlease do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
 
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
 
ECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docx
 
ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata
 
Ashish garg research paper 660_CamReady
Ashish garg research paper 660_CamReadyAshish garg research paper 660_CamReady
Ashish garg research paper 660_CamReady
 
Database Sizing
Database SizingDatabase Sizing
Database Sizing
 
Static code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xStatic code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0x
 
Static code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0xStatic code analysis and the new language standard C++0x
Static code analysis and the new language standard C++0x
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 

Mais de Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trieSomenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidSomenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docsSomenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsSomenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureSomenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternSomenath Mukhopadhyay
 

Mais de Somenath Mukhopadhyay (20)

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 

Último

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 

Memory layout in C++ vis a-vis polymorphism and padding bits

  • 1. SOM-ITSOLUTIONS C++ Memory layout in C++ vis-a-vis Polymorphism and Padding bits SOMENATH MUKHOPADHYAY som-itsolutions #A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282 Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com Website: ​www.som-itsolutions.com Blog:​ www.som-itsolutions.blogspot.com
  • 2. I know there is no need for the knowledge of memory layout for a normal day-to-day development of C++. However, when someone goes in the bit/byte level of C++, he needs looks for such discussion. To state the problem, let us have a class hierarchy like the following. class​ ​A​ { ​public​: ​virtual​ ​void​ funA() {} ​virtual​ ​~​A(){} public​: ​int​ a; }; class​ ​B​ { ​public​: ​virtual​ ​void​ funB(){}; ​virtual​ ​~​B(){} public​: ​int​ b; }; class​ ​C​ ​:​ ​public​ A, ​public​ B { public​: ​int​ c; }; Now if we run this app using a GCC compiler on a 64 bit machine and see the sizeof() these classes, we will see A will be 16 byte, B will be 16 byte and C will be of 32 bytes . So lets discuss how these numbers have come. To start with the discussion, i need to throw some lights about how polymorphic behavior in C++ using virtual functions is tackeled by a compiler. Whenever there is a class having virtual function, the compiler will generate a VTABLE of that class and all the objects of that class will use that VTABLE. VTABLE is nothing but a TABLE having pointers to the virtual functions in a class hierarchy. And whenever there is a VTABLE, the compiler will silently add a pointer in the beginning of an object of the class. This pointer is called vptr and it actually points to the beginning of the VTABLE. 2​ | ​Page
  • 3. So in the following case two VTABLES will be created (each for class A and B). Hence the size of an object of class A will be size-of-a-pointer(vptr) + size-of-int. So for a 64 bit architecture (where a pointer is 8 byte long) it will be 8 + 4 = 12. If this is the case, then how come sizeof(A) shows 16. Here comes the concept of Alignment and Padding bits. Here is an excerpt from Wiki about alignment. "A memory address a, is said to be n-byte aligned when a is a multiple of n bytes (where n is a power of 2). In this context a byte is the smallest unit of memory access, i.e. each memory address specifies a different byte. An n-byte aligned address would have log2(n) least-significant zeros when expressed in binary. The alternate wording b-bit aligned designates a b/8 byte aligned address (ex. 64-bit aligned is 8 bytes aligned). A memory access is said to be aligned when the datum being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned. A memory pointer that refers to primitive data that is n bytes long is said to be aligned if it is only allowed to contain addresses that are n-byte aligned, otherwise it is said to be unaligned. A memory pointer that refers to a data aggregate (a data structure or array) is aligned if (and only if) each primitive datum in the aggregate is aligned. Note that the definitions above assume that each primitive datum is a power of two bytes long. When this is not the case (as with 80-bit floating-point on x86) the context influences the conditions where the datum is considered aligned or not. Data structures can be stored in memory on the stack with a static size known as bounded or on the heap with a dynamic size known as unbounded." To maintain the alignment, compiler inserts padding bits in the compiled code of a structure/class object. "Although the compiler (or interpreter) normally allocates individual data items on aligned boundaries, data structures often have members with different alignment requirements. To maintain proper alignment the translator normally inserts additional unnamed data members so that each member is properly aligned. In 3​ | ​Page
  • 4. addition the data structure as a whole may be padded with a final unnamed member. This allows each member of an array of structures to be properly aligned. .... .... Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure" - Wiki To get more info about how GCC does it, please look at http://www.delorie.com/gnu/docs/gcc/gccint_111.html and search for the text "basic-align". Now lets come to this problem: Using the example class, i have created this program for a GCC compiler running on a 64 bit Ubuntu. int​ ​main​() { A objA; C objC; cout​<<​sizeof​(​void​*​)​<<​endl; cout​<<​sizeof​(​int​)​<<​endl; cout​<<​sizeof​(A)​<<​endl; cout​<<​sizeof​(B)​<<​endl; cout​<<​sizeof​(C)​<<​endl; ​return​ ​0​; } And the result for this program is as the following: 8 4 16 16 4​ | ​Page
  • 5. 32 As i was saying that object of class A will have a VPTR (pointing to the VTABLE of A) and an int. The pointer will be 8 byte long and the int will be 4 byte long. Hence before compile the size is 12 bytes. But the compiler will add extra 4 bytes at the end of int a as padding bits to maintain the alignment of class A equal to the highest length of the data member of the class which is divisible by 2, that is vPtr (8 byte long). Hence after compilation, the A's objects size will be 12 + 4 = 16 bytes. Similarly for class B's objects. Now object of C will have two VPTRs (one for each class A & class B) and 3 ints (a,b,c). So normally the size of object of C should have been 8 + 8 + 3*4 = 28 bytes. But here is what happens because the compiler adds padding bytes. After the addition of the padding bytes, the size becomes 8 (VPTR A) + 4 (int a) + 4 (padding bytes) + 8 (VPTR B) + 4 (int b) + 4 (int c) = 32 bytes. So the total size of C will be 32 bytes. Note: Type this to see the memory dump on the screen using gcc compiler g++ -fdump-class-hierarchy=stdout MemoryLayout.cpp where ​MemoryLayout.cpp ​is the file containing the class hierarchy… 5​ | ​Page