SlideShare a Scribd company logo
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.".

More Related Content

What's hot (18)

PPTX
C++ lab -4
سلمى شطا
 
PDF
Cs2303 theory of computation november december 2015
appasami
 
ODT
Ecet 330 final exam new 2016
sergejsvolkovs10
 
PPTX
Lecture 3: Strings and Dynamic Memory Allocation
Vivek Bhargav
 
PPTX
Combinational Circuits
Dilum Bandara
 
DOCX
Parallel Adder
Soudip Sinha Roy
 
PDF
CBSE Question Paper Computer Science with C++ 2011
Deepak Singh
 
PPTX
Digital logic circuit
Prabhu R
 
PPTX
CSC – 184 Programming C
ABIR A HAPZU
 
DOC
8
satishbb
 
PDF
15CS664- Python Application Programming- Question bank 1
Syed Mustafa
 
PDF
Prepostinfix
MohitKumawat27
 
PPTX
Exercise6 ch2
IIUM
 
PPTX
C string
University of Potsdam
 
PPTX
Adder ppt
Avinash Jadhav
 
PPTX
Cpu.ppt INTRODUCTION TO “C”
Sukhvinder Singh
 
PDF
15CS664 Python Question Bank-3
Syed Mustafa
 
PDF
Ec2203 digital electronics questions anna university by www.annaunivedu.org
annaunivedu
 
C++ lab -4
سلمى شطا
 
Cs2303 theory of computation november december 2015
appasami
 
Ecet 330 final exam new 2016
sergejsvolkovs10
 
Lecture 3: Strings and Dynamic Memory Allocation
Vivek Bhargav
 
Combinational Circuits
Dilum Bandara
 
Parallel Adder
Soudip Sinha Roy
 
CBSE Question Paper Computer Science with C++ 2011
Deepak Singh
 
Digital logic circuit
Prabhu R
 
CSC – 184 Programming C
ABIR A HAPZU
 
15CS664- Python Application Programming- Question bank 1
Syed Mustafa
 
Prepostinfix
MohitKumawat27
 
Exercise6 ch2
IIUM
 
Adder ppt
Avinash Jadhav
 
Cpu.ppt INTRODUCTION TO “C”
Sukhvinder Singh
 
15CS664 Python Question Bank-3
Syed Mustafa
 
Ec2203 digital electronics questions anna university by www.annaunivedu.org
annaunivedu
 

Similar to A nice 64-bit error in C (20)

PDF
Lesson 9. Pattern 1. Magic numbers
PVS-Studio
 
PDF
A collection of examples of 64 bit errors in real programs
Michael Scovetta
 
PDF
A Collection of Examples of 64-bit Errors in Real Programs
PVS-Studio
 
PDF
A Collection of Examples of 64-bit Errors in Real Programs
Andrey Karpov
 
PDF
Development of a static code analyzer for detecting errors of porting program...
PVS-Studio
 
PDF
Undefined behavior is closer than you think
Andrey Karpov
 
PDF
Monitoring a program that monitors computer networks
Andrey Karpov
 
PPTX
Patterns of 64-bit errors in games
Andrey Karpov
 
PDF
Lesson 6. Errors in 64-bit code
PVS-Studio
 
PDF
Software diseases: memset
PVS-Studio
 
PDF
Lesson 10. Pattern 2. Functions with variable number of arguments
PVS-Studio
 
PDF
A 64-bit horse that can count
Andrey Karpov
 
PDF
The article is a report about testing of portability of Loki library with 64-...
PVS-Studio
 
PDF
Lesson 13. Pattern 5. Address arithmetic
PVS-Studio
 
PDF
Safety of 64-bit code
PVS-Studio
 
PDF
C++11 and 64-bit Issues
Andrey Karpov
 
PPTX
What has to be paid attention when reviewing code of the library you develop
Andrey Karpov
 
PDF
Lesson 17. Pattern 9. Mixed arithmetic
PVS-Studio
 
PDF
64-Bit Code in 2015: New in the Diagnostics of Possible Issues
PVS-Studio
 
PDF
Lesson 24. Phantom errors
PVS-Studio
 
Lesson 9. Pattern 1. Magic numbers
PVS-Studio
 
A collection of examples of 64 bit errors in real programs
Michael Scovetta
 
A Collection of Examples of 64-bit Errors in Real Programs
PVS-Studio
 
A Collection of Examples of 64-bit Errors in Real Programs
Andrey Karpov
 
Development of a static code analyzer for detecting errors of porting program...
PVS-Studio
 
Undefined behavior is closer than you think
Andrey Karpov
 
Monitoring a program that monitors computer networks
Andrey Karpov
 
Patterns of 64-bit errors in games
Andrey Karpov
 
Lesson 6. Errors in 64-bit code
PVS-Studio
 
Software diseases: memset
PVS-Studio
 
Lesson 10. Pattern 2. Functions with variable number of arguments
PVS-Studio
 
A 64-bit horse that can count
Andrey Karpov
 
The article is a report about testing of portability of Loki library with 64-...
PVS-Studio
 
Lesson 13. Pattern 5. Address arithmetic
PVS-Studio
 
Safety of 64-bit code
PVS-Studio
 
C++11 and 64-bit Issues
Andrey Karpov
 
What has to be paid attention when reviewing code of the library you develop
Andrey Karpov
 
Lesson 17. Pattern 9. Mixed arithmetic
PVS-Studio
 
64-Bit Code in 2015: New in the Diagnostics of Possible Issues
PVS-Studio
 
Lesson 24. Phantom errors
PVS-Studio
 
Ad

Recently uploaded (20)

PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Ad

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.".