SlideShare uma empresa Scribd logo
1 de 2
Baixar para ler offline
A nice 64-bit error in C
Author: Andrey Karpov

Date: 19.11.2009

In C language, you may use functions without defining them. Pay attention that I speak about C
language, not C++. Of course, this ability is very dangerous. Let us have a look at an interesting example
of a 64-bit error related to it. Below is the correct code that allocates and uses three arrays, 1 GB each:

#include <stdlib.h>

void test()

{

    const size_t Gbyte = 1024 * 1024 * 1024;

    size_t i;

    char *Pointers[3];

    // Allocate

    for (i = 0; i != 3; ++i)

      Pointers[i] = (char *)malloc(Gbyte);

    // Use

    for (i = 0; i != 3; ++i)

      Pointers[i][0] = 1;

    // Free

    for (i = 0; i != 3; ++i)

      free(Pointers[i]);

}

This code correctly allocates memory, writes one into the first item of each array and frees the allocated
memory. The code is absolutely correct on a 64-bit system.

Now delete or comment the line "#include <stdlib.h>". The code still compiles but the program crashes
after the launch. As the header file "stdlib.h" is disabled, the C compiler considers that malloc function
will return int type. The first two allocations are most likely to be successful. After the third call, malloc
function will return the array's address outside the range of the first two Gbyte. As the compiler
considers the function's result to have int type, it interprets the result incorrectly and saves the incorrect
value of the pointer in Pointers array.
To make it clearer, let us consider an assembler code generated by Visual C++ compiler for the 64-bit
Debug version. At first look at the correct code generated when malloc function is defined (i.e. the file
"stdlib.h" is included):

Pointers[i] = (char *)malloc(Gbyte);

mov      rcx,qword ptr [Gbyte]

call     qword ptr [__imp_malloc (14000A518h)]

mov       rcx,qword ptr [i]

mov       qword ptr Pointers[rcx*8],rax

Now consider the variant of the incorrect code when malloc function is not defined:

Pointers[i] = (char *)malloc(Gbyte);

mov       rcx,qword ptr [Gbyte]

call      malloc (1400011A6h)

cdqe

mov       rcx,qword ptr [i]

mov       qword ptr Pointers[rcx*8],rax

Consider the CDQE instruction (Convert doubleword to quadword). The compiler supposed the result to
be kept in eax registers and extended it to a 64-bit value to write into Pointers array. Respectively, the
high-order bits of rax register are lost. Even if the address of the allocated memory is inside the range of
the first 4 GB, we still get the incorrect result when the high-order bit of eax register equals 1. For
example, the address 0x81000000 turns into 0xFFFFFFFF81000000.

Fortunately, this type of errors is easy to define. For example, Visual C++ compiler generates two
warnings informing about a potential problem:

warning C4013: 'malloc' undefined; assuming extern returning int
warning C4312: 'type cast' : conversion from 'int' to 'char *' of greater size

And PVS-Studio 3.40 analyzer generates the warning "error V201: Explicit type conversion. Type casting
to memsize.".

Mais conteúdo relacionado

Mais procurados

Cs2303 theory of computation november december 2015
Cs2303 theory of computation november december 2015Cs2303 theory of computation november december 2015
Cs2303 theory of computation november december 2015appasami
 
Ecet 330 final exam new 2016
Ecet 330 final exam new 2016Ecet 330 final exam new 2016
Ecet 330 final exam new 2016sergejsvolkovs10
 
Lecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationLecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationVivek Bhargav
 
Combinational Circuits
Combinational CircuitsCombinational Circuits
Combinational CircuitsDilum Bandara
 
CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011Deepak Singh
 
Digital logic circuit
Digital logic circuit Digital logic circuit
Digital logic circuit Prabhu R
 
CSC – 184 Programming C
CSC – 184 Programming CCSC – 184 Programming C
CSC – 184 Programming CABIR A HAPZU
 
15CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 115CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 1Syed Mustafa
 
Exercise6 ch2
Exercise6 ch2Exercise6 ch2
Exercise6 ch2IIUM
 
Cpu.ppt INTRODUCTION TO “C”
Cpu.ppt INTRODUCTION TO “C” Cpu.ppt INTRODUCTION TO “C”
Cpu.ppt INTRODUCTION TO “C” Sukhvinder Singh
 
15CS664 Python Question Bank-3
15CS664 Python Question Bank-315CS664 Python Question Bank-3
15CS664 Python Question Bank-3Syed Mustafa
 
Ec2203 digital electronics questions anna university by www.annaunivedu.org
Ec2203 digital electronics questions anna university by www.annaunivedu.orgEc2203 digital electronics questions anna university by www.annaunivedu.org
Ec2203 digital electronics questions anna university by www.annaunivedu.organnaunivedu
 

Mais procurados (18)

C++ lab -4
C++ lab -4C++ lab -4
C++ lab -4
 
Cs2303 theory of computation november december 2015
Cs2303 theory of computation november december 2015Cs2303 theory of computation november december 2015
Cs2303 theory of computation november december 2015
 
Ecet 330 final exam new 2016
Ecet 330 final exam new 2016Ecet 330 final exam new 2016
Ecet 330 final exam new 2016
 
Lecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationLecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory Allocation
 
Combinational Circuits
Combinational CircuitsCombinational Circuits
Combinational Circuits
 
Parallel Adder
Parallel Adder Parallel Adder
Parallel Adder
 
CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011
 
Digital logic circuit
Digital logic circuit Digital logic circuit
Digital logic circuit
 
CSC – 184 Programming C
CSC – 184 Programming CCSC – 184 Programming C
CSC – 184 Programming C
 
8
88
8
 
15CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 115CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 1
 
Prepostinfix
PrepostinfixPrepostinfix
Prepostinfix
 
Exercise6 ch2
Exercise6 ch2Exercise6 ch2
Exercise6 ch2
 
C string
C stringC string
C string
 
Adder ppt
Adder pptAdder ppt
Adder ppt
 
Cpu.ppt INTRODUCTION TO “C”
Cpu.ppt INTRODUCTION TO “C” Cpu.ppt INTRODUCTION TO “C”
Cpu.ppt INTRODUCTION TO “C”
 
15CS664 Python Question Bank-3
15CS664 Python Question Bank-315CS664 Python Question Bank-3
15CS664 Python Question Bank-3
 
Ec2203 digital electronics questions anna university by www.annaunivedu.org
Ec2203 digital electronics questions anna university by www.annaunivedu.orgEc2203 digital electronics questions anna university by www.annaunivedu.org
Ec2203 digital electronics questions anna university by www.annaunivedu.org
 

Semelhante a A nice 64-bit error in C

C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit IssuesAndrey Karpov
 
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
 
What has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developWhat has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developAndrey Karpov
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++PVS-Studio
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centrejatin batra
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-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
 
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
 
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
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitAndrey 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
 
Undefined behavior is closer than you think
Undefined behavior is closer than you thinkUndefined behavior is closer than you think
Undefined behavior is closer than you thinkAndrey Karpov
 
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
 
Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...PVS-Studio
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projectsPVS-Studio
 

Semelhante a A nice 64-bit error in C (20)

C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
 
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
 
What has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developWhat has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you develop
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmetic
 
8871077.ppt
8871077.ppt8871077.ppt
8871077.ppt
 
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
 
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
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGit
 
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
 
Undefined behavior is closer than you think
Undefined behavior is closer than you thinkUndefined behavior is closer than you think
Undefined behavior is closer than you think
 
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
 
Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...
 
C interview questions
C interview questionsC interview questions
C interview questions
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 

Último

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

A nice 64-bit error in C

  • 1. A nice 64-bit error in C Author: Andrey Karpov Date: 19.11.2009 In C language, you may use functions without defining them. Pay attention that I speak about C language, not C++. Of course, this ability is very dangerous. Let us have a look at an interesting example of a 64-bit error related to it. Below is the correct code that allocates and uses three arrays, 1 GB each: #include <stdlib.h> void test() { const size_t Gbyte = 1024 * 1024 * 1024; size_t i; char *Pointers[3]; // Allocate for (i = 0; i != 3; ++i) Pointers[i] = (char *)malloc(Gbyte); // Use for (i = 0; i != 3; ++i) Pointers[i][0] = 1; // Free for (i = 0; i != 3; ++i) free(Pointers[i]); } This code correctly allocates memory, writes one into the first item of each array and frees the allocated memory. The code is absolutely correct on a 64-bit system. Now delete or comment the line "#include <stdlib.h>". The code still compiles but the program crashes after the launch. As the header file "stdlib.h" is disabled, the C compiler considers that malloc function will return int type. The first two allocations are most likely to be successful. After the third call, malloc function will return the array's address outside the range of the first two Gbyte. As the compiler considers the function's result to have int type, it interprets the result incorrectly and saves the incorrect value of the pointer in Pointers array.
  • 2. To make it clearer, let us consider an assembler code generated by Visual C++ compiler for the 64-bit Debug version. At first look at the correct code generated when malloc function is defined (i.e. the file "stdlib.h" is included): Pointers[i] = (char *)malloc(Gbyte); mov rcx,qword ptr [Gbyte] call qword ptr [__imp_malloc (14000A518h)] mov rcx,qword ptr [i] mov qword ptr Pointers[rcx*8],rax Now consider the variant of the incorrect code when malloc function is not defined: Pointers[i] = (char *)malloc(Gbyte); mov rcx,qword ptr [Gbyte] call malloc (1400011A6h) cdqe mov rcx,qword ptr [i] mov qword ptr Pointers[rcx*8],rax Consider the CDQE instruction (Convert doubleword to quadword). The compiler supposed the result to be kept in eax registers and extended it to a 64-bit value to write into Pointers array. Respectively, the high-order bits of rax register are lost. Even if the address of the allocated memory is inside the range of the first 4 GB, we still get the incorrect result when the high-order bit of eax register equals 1. For example, the address 0x81000000 turns into 0xFFFFFFFF81000000. Fortunately, this type of errors is easy to define. For example, Visual C++ compiler generates two warnings informing about a potential problem: warning C4013: 'malloc' undefined; assuming extern returning int warning C4312: 'type cast' : conversion from 'int' to 'char *' of greater size And PVS-Studio 3.40 analyzer generates the warning "error V201: Explicit type conversion. Type casting to memsize.".