SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
Lesson 21. Pattern 13. Data alignment
Processors work more efficiently when the data are aligned properly and some processors cannot work
with non-aligned data at all. When you try to work with non-aligned data on IA-64 (Itanium) processors,
it will lead to generating an exception, as shown in the following example:

#pragma pack (1) // Also set by key /Zp in MSVC

struct AlignSample {

    unsigned size;

    void *pointer;

} object;

void foo(void *p) {

    object.pointer = p; // Alignment fault

}

If you have to work with non-aligned data on Itanium, you should specify this explicitly to the compiler.
For example, you may use a special macro UNALIGNED:

#pragma pack (1) // Also set by key /Zp in MSVC

struct AlignSample {

    unsigned size;

    void *pointer;

} object;

void foo(void *p) {

    *(UNALIGNED void *)&object.pointer = p; //Very slow

}

In this case the compiler generates a special code to deal with the non-aligned data. It is not very
efficient since the access to the data will be several times slower. If your purpose is to make the
structure's size smaller, you can get the best result arranging the data in decreasing order of their sizes.
We will speak about it in more detail in one of the next lessons.

Exceptions are not generated when you address non-aligned data on the architecture x64 but you still
should avoid them - first, because the access to these data is very much slower, and second, because
you may want to port the program to the platform IA-64 in the future.

Consider one more code sample that does not consider the data alignment:

struct MyPointersArray {

    DWORD m_n;
PVOID m_arr[1];

} object;

...

malloc( sizeof(DWORD) + 5 * sizeof(PVOID) );

...

If we want to allocate an amount of memory needed to store an object of MyPointersArray type that
contains 5 pointers, we should consider that the beginning of the array m_arr will be aligned on an 8-
byte boundary. The arrangement of data in memory in various systems (Win32/Win64) is shown in
Figure 1.




                    Figure 1- Data alignment in memory in Win32 and Win64 systems

The correct calculation of the size looks as follows:

struct MyPointersArray {

   DWORD m_n;

   PVOID m_arr[1];

} object;

...

malloc( FIELD_OFFSET(struct MyPointersArray, m_arr) +

            5 * sizeof(PVOID) );

...
In this code we find out the offset of the structure's last member and add this value to its size. You can
find out the offset of a structure's or class's member with the help of the macro "offsetof" or
FIELD_OFFSET.

Always use these macros to know the offset in the structure without relying on knowing the types' sizes
and alignment. Here is an example of code where the address of a structure's member is calculated
correctly:

struct TFoo {

   DWORD_PTR whatever;

   int value;

} object;

int *valuePtr =

   (int *)((size_t)(&object) + offsetof(TFoo, value)); // OK

Linux-developers may encounter one more trouble related to alignment. You may learn what it is from
our blog-post "Change of type alignment and the consequences".


Diagnosis
Since work with non-aligned data does not cause an error on the x64 architecture and only reduces
performance, the tool PVS-Studio does not warn you about packed structures. But if the performance of
an application is crucial to you, we recommend you to look through all the fragments in the program
where "#pragma pack" is used. This is more relevant for the architecture IA-64 but PVS-Studio analyzer
is not designed to verify programs for IA-64 yet. If you deal with Itanium-based systems and are planning
to purchase PVS-Studio, write to us and we will discuss the issues of adapting our tool to IA-64 specifics.

PVS-Studio tool allows you to find errors related to calculation of objects' sizes and offsets. The analyzer
detects dangerous arithmetic expressions containing several operators sizeof() (it signals a potential
error). The number of the corresponding diagnostic message is V119.

However, it is correct in many cases to use several sizeof() operators in one expression and the analyzer
ignores such constructs. Here is an example of safe expressions with several sizeof operators:

int MyArray[] = { 1, 2, 3 };

size_t MyArraySize =

   sizeof(MyArray) / sizeof(MyArray[0]); //OK

assert(sizeof(unsigned) < sizeof(size_t)); //OK

size_t strLen = sizeof(String) - sizeof(TCHAR); //OK
Appendix
Figure 2 represents types' sizes and their alignment. To learn about objects' sizes and their alignment on
various platforms, see the code sample given in the blog-post "Change of type alignment and the
consequences".




                               Figure 2 - Types' sizes and their alignment.

The course authors: Andrey Karpov (karpov@viva64.com), Evgeniy Ryzhkov (evg@viva64.com).

The rightholder of the course "Lessons on development of 64-bit C/C++ applications" is OOO "Program
Verification Systems". The company develops software in the sphere of source program code analysis.
The company's site: http://www.viva64.com.
Contacts: e-mail: support@viva64.com, Tula, 300027, PO box 1800.

Mais conteúdo relacionado

Mais procurados

Uses Of Calculus is Computer Science
Uses Of Calculus is Computer ScienceUses Of Calculus is Computer Science
Uses Of Calculus is Computer ScienceArnob Khan
 
Ml study notes id3
Ml study notes   id3Ml study notes   id3
Ml study notes id3Feri Handoyo
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languagetanmaymodi4
 
Dot net parallelism and multicore computing
Dot net parallelism and multicore computingDot net parallelism and multicore computing
Dot net parallelism and multicore computingAravindhan Gnanam
 
Presentation on application of matrix
Presentation on application of matrixPresentation on application of matrix
Presentation on application of matrixPrerana Bhattarai
 
Matrix and it's Application
Matrix and it's ApplicationMatrix and it's Application
Matrix and it's ApplicationMahmudle Hassan
 
Using visual basic for applications (vba)
Using visual basic for applications (vba)Using visual basic for applications (vba)
Using visual basic for applications (vba)Javier Morales Cauna
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cMd Nazmul Hossain Mir
 
Svm Presentation
Svm PresentationSvm Presentation
Svm Presentationshahparin
 
Concepts of Arrays
Concepts of ArraysConcepts of Arrays
Concepts of ArraysYashh Pandya
 
Applications of matrices in real life
Applications of matrices in real lifeApplications of matrices in real life
Applications of matrices in real lifeSuhaibFaiz
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 

Mais procurados (20)

Uses Of Calculus is Computer Science
Uses Of Calculus is Computer ScienceUses Of Calculus is Computer Science
Uses Of Calculus is Computer Science
 
Ml study notes id3
Ml study notes   id3Ml study notes   id3
Ml study notes id3
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Dot net parallelism and multicore computing
Dot net parallelism and multicore computingDot net parallelism and multicore computing
Dot net parallelism and multicore computing
 
Bitstuffing
BitstuffingBitstuffing
Bitstuffing
 
Presentation on application of matrix
Presentation on application of matrixPresentation on application of matrix
Presentation on application of matrix
 
C programming part4
C programming part4C programming part4
C programming part4
 
Diagrams
DiagramsDiagrams
Diagrams
 
Matrix and it's Application
Matrix and it's ApplicationMatrix and it's Application
Matrix and it's Application
 
Error analysis
Error analysisError analysis
Error analysis
 
Uniterm indexing
Uniterm indexing Uniterm indexing
Uniterm indexing
 
Mmt 001
Mmt 001Mmt 001
Mmt 001
 
Using visual basic for applications (vba)
Using visual basic for applications (vba)Using visual basic for applications (vba)
Using visual basic for applications (vba)
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-c
 
Svm Presentation
Svm PresentationSvm Presentation
Svm Presentation
 
Concepts of Arrays
Concepts of ArraysConcepts of Arrays
Concepts of Arrays
 
Applications of matrices in real life
Applications of matrices in real lifeApplications of matrices in real life
Applications of matrices in real life
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 

Destaque

VivaMP - a tool for OpenMP
VivaMP - a tool for OpenMPVivaMP - a tool for OpenMP
VivaMP - a tool for OpenMPPVS-Studio
 
Parallel programs to multi-processor computers!
Parallel programs to multi-processor computers!Parallel programs to multi-processor computers!
Parallel programs to multi-processor computers!PVS-Studio
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team developmentPVS-Studio
 
PVS-Studio, a solution for developers of modern resource-intensive applications
PVS-Studio, a solution for developers of modern resource-intensive applicationsPVS-Studio, a solution for developers of modern resource-intensive applications
PVS-Studio, a solution for developers of modern resource-intensive applicationsPVS-Studio
 
Changes in programmer tools' infrastructure
Changes in programmer tools' infrastructureChanges in programmer tools' infrastructure
Changes in programmer tools' infrastructurePVS-Studio
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsPVS-Studio
 
Description of VivaVisualCode
Description of VivaVisualCodeDescription of VivaVisualCode
Description of VivaVisualCodePVS-Studio
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio
 
How VivaCore library appeared
How VivaCore library appearedHow VivaCore library appeared
How VivaCore library appearedPVS-Studio
 
Lesson 16. Pattern 8. Memsize-types in unions
Lesson 16. Pattern 8. Memsize-types in unionsLesson 16. Pattern 8. Memsize-types in unions
Lesson 16. Pattern 8. Memsize-types in unionsPVS-Studio
 
Lesson 19. Pattern 11. Serialization and data interchange
Lesson 19. Pattern 11. Serialization and data interchangeLesson 19. Pattern 11. Serialization and data interchange
Lesson 19. Pattern 11. Serialization and data interchangePVS-Studio
 
Testing parallel programs
Testing parallel programsTesting parallel programs
Testing parallel programsPVS-Studio
 
Introduction into the problems of developing parallel programs
Introduction into the problems of developing parallel programsIntroduction into the problems of developing parallel programs
Introduction into the problems of developing parallel programsPVS-Studio
 
Analysis of the Ultimate Toolbox project
Analysis of the Ultimate Toolbox projectAnalysis of the Ultimate Toolbox project
Analysis of the Ultimate Toolbox projectPVS-Studio
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errorsPVS-Studio
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...PVS-Studio
 

Destaque (16)

VivaMP - a tool for OpenMP
VivaMP - a tool for OpenMPVivaMP - a tool for OpenMP
VivaMP - a tool for OpenMP
 
Parallel programs to multi-processor computers!
Parallel programs to multi-processor computers!Parallel programs to multi-processor computers!
Parallel programs to multi-processor computers!
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team development
 
PVS-Studio, a solution for developers of modern resource-intensive applications
PVS-Studio, a solution for developers of modern resource-intensive applicationsPVS-Studio, a solution for developers of modern resource-intensive applications
PVS-Studio, a solution for developers of modern resource-intensive applications
 
Changes in programmer tools' infrastructure
Changes in programmer tools' infrastructureChanges in programmer tools' infrastructure
Changes in programmer tools' infrastructure
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programs
 
Description of VivaVisualCode
Description of VivaVisualCodeDescription of VivaVisualCode
Description of VivaVisualCode
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs Chromium
 
How VivaCore library appeared
How VivaCore library appearedHow VivaCore library appeared
How VivaCore library appeared
 
Lesson 16. Pattern 8. Memsize-types in unions
Lesson 16. Pattern 8. Memsize-types in unionsLesson 16. Pattern 8. Memsize-types in unions
Lesson 16. Pattern 8. Memsize-types in unions
 
Lesson 19. Pattern 11. Serialization and data interchange
Lesson 19. Pattern 11. Serialization and data interchangeLesson 19. Pattern 11. Serialization and data interchange
Lesson 19. Pattern 11. Serialization and data interchange
 
Testing parallel programs
Testing parallel programsTesting parallel programs
Testing parallel programs
 
Introduction into the problems of developing parallel programs
Introduction into the problems of developing parallel programsIntroduction into the problems of developing parallel programs
Introduction into the problems of developing parallel programs
 
Analysis of the Ultimate Toolbox project
Analysis of the Ultimate Toolbox projectAnalysis of the Ultimate Toolbox project
Analysis of the Ultimate Toolbox project
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 

Semelhante a Lesson 21. Pattern 13. Data alignment

Exploring Microoptimizations Using Tizen Code as an Example
Exploring Microoptimizations Using Tizen Code as an ExampleExploring Microoptimizations Using Tizen Code as an Example
Exploring Microoptimizations Using Tizen Code as an ExamplePVS-Studio
 
Lesson 26. Optimization of 64-bit programs
Lesson 26. Optimization of 64-bit programsLesson 26. Optimization of 64-bit programs
Lesson 26. Optimization of 64-bit programsPVS-Studio
 
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codeComparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codePVS-Studio
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfacsmadurai
 
A Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsA Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsPVS-Studio
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private DataPVS-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
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioRobert Tanenbaum
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...VLSICS Design
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckAndrey Karpov
 
A Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsA Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsAndrey Karpov
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
About size_t and ptrdiff_t
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_tPVS-Studio
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Final report mobile shop
Final report   mobile shopFinal report   mobile shop
Final report mobile shopViditsingh22
 

Semelhante a Lesson 21. Pattern 13. Data alignment (20)

Exploring Microoptimizations Using Tizen Code as an Example
Exploring Microoptimizations Using Tizen Code as an ExampleExploring Microoptimizations Using Tizen Code as an Example
Exploring Microoptimizations Using Tizen Code as an Example
 
Grounded Pointers
Grounded PointersGrounded Pointers
Grounded Pointers
 
Lesson 26. Optimization of 64-bit programs
Lesson 26. Optimization of 64-bit programsLesson 26. Optimization of 64-bit programs
Lesson 26. Optimization of 64-bit programs
 
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codeComparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
 
A Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsA Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real Programs
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
 
BIT211_2.pdf
BIT211_2.pdfBIT211_2.pdf
BIT211_2.pdf
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmetic
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net Portfolio
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
A Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real ProgramsA Collection of Examples of 64-bit Errors in Real Programs
A Collection of Examples of 64-bit Errors in Real Programs
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
About size_t and ptrdiff_t
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_t
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Final report mobile shop
Final report   mobile shopFinal report   mobile shop
Final report mobile shop
 

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Último (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Lesson 21. Pattern 13. Data alignment

  • 1. Lesson 21. Pattern 13. Data alignment Processors work more efficiently when the data are aligned properly and some processors cannot work with non-aligned data at all. When you try to work with non-aligned data on IA-64 (Itanium) processors, it will lead to generating an exception, as shown in the following example: #pragma pack (1) // Also set by key /Zp in MSVC struct AlignSample { unsigned size; void *pointer; } object; void foo(void *p) { object.pointer = p; // Alignment fault } If you have to work with non-aligned data on Itanium, you should specify this explicitly to the compiler. For example, you may use a special macro UNALIGNED: #pragma pack (1) // Also set by key /Zp in MSVC struct AlignSample { unsigned size; void *pointer; } object; void foo(void *p) { *(UNALIGNED void *)&object.pointer = p; //Very slow } In this case the compiler generates a special code to deal with the non-aligned data. It is not very efficient since the access to the data will be several times slower. If your purpose is to make the structure's size smaller, you can get the best result arranging the data in decreasing order of their sizes. We will speak about it in more detail in one of the next lessons. Exceptions are not generated when you address non-aligned data on the architecture x64 but you still should avoid them - first, because the access to these data is very much slower, and second, because you may want to port the program to the platform IA-64 in the future. Consider one more code sample that does not consider the data alignment: struct MyPointersArray { DWORD m_n;
  • 2. PVOID m_arr[1]; } object; ... malloc( sizeof(DWORD) + 5 * sizeof(PVOID) ); ... If we want to allocate an amount of memory needed to store an object of MyPointersArray type that contains 5 pointers, we should consider that the beginning of the array m_arr will be aligned on an 8- byte boundary. The arrangement of data in memory in various systems (Win32/Win64) is shown in Figure 1. Figure 1- Data alignment in memory in Win32 and Win64 systems The correct calculation of the size looks as follows: struct MyPointersArray { DWORD m_n; PVOID m_arr[1]; } object; ... malloc( FIELD_OFFSET(struct MyPointersArray, m_arr) + 5 * sizeof(PVOID) ); ...
  • 3. In this code we find out the offset of the structure's last member and add this value to its size. You can find out the offset of a structure's or class's member with the help of the macro "offsetof" or FIELD_OFFSET. Always use these macros to know the offset in the structure without relying on knowing the types' sizes and alignment. Here is an example of code where the address of a structure's member is calculated correctly: struct TFoo { DWORD_PTR whatever; int value; } object; int *valuePtr = (int *)((size_t)(&object) + offsetof(TFoo, value)); // OK Linux-developers may encounter one more trouble related to alignment. You may learn what it is from our blog-post "Change of type alignment and the consequences". Diagnosis Since work with non-aligned data does not cause an error on the x64 architecture and only reduces performance, the tool PVS-Studio does not warn you about packed structures. But if the performance of an application is crucial to you, we recommend you to look through all the fragments in the program where "#pragma pack" is used. This is more relevant for the architecture IA-64 but PVS-Studio analyzer is not designed to verify programs for IA-64 yet. If you deal with Itanium-based systems and are planning to purchase PVS-Studio, write to us and we will discuss the issues of adapting our tool to IA-64 specifics. PVS-Studio tool allows you to find errors related to calculation of objects' sizes and offsets. The analyzer detects dangerous arithmetic expressions containing several operators sizeof() (it signals a potential error). The number of the corresponding diagnostic message is V119. However, it is correct in many cases to use several sizeof() operators in one expression and the analyzer ignores such constructs. Here is an example of safe expressions with several sizeof operators: int MyArray[] = { 1, 2, 3 }; size_t MyArraySize = sizeof(MyArray) / sizeof(MyArray[0]); //OK assert(sizeof(unsigned) < sizeof(size_t)); //OK size_t strLen = sizeof(String) - sizeof(TCHAR); //OK
  • 4. Appendix Figure 2 represents types' sizes and their alignment. To learn about objects' sizes and their alignment on various platforms, see the code sample given in the blog-post "Change of type alignment and the consequences". Figure 2 - Types' sizes and their alignment. The course authors: Andrey Karpov (karpov@viva64.com), Evgeniy Ryzhkov (evg@viva64.com). The rightholder of the course "Lessons on development of 64-bit C/C++ applications" is OOO "Program Verification Systems". The company develops software in the sphere of source program code analysis. The company's site: http://www.viva64.com.
  • 5. Contacts: e-mail: support@viva64.com, Tula, 300027, PO box 1800.