SlideShare uma empresa Scribd logo
1 de 2
Baixar para ler offline
The Joy of Programming
Allocation of Local Variables in Stack

It is always fun to understand the low-level details of a program and to explore how compilers
work. In this column, we’ll see some details on how local variables are allocated in stack and
some interesting issues on how compilers handle it.

Every month, I get lots of mails and queries from LFY readers. This column seems to have become
popular, particularly among students. This month, we’ll cover an interesting question from
Saravanan swamy (GCT, Coimbatore). His question is: Why does the following program print 10?
        int i = 10;
        printf(“%d”);

Note that the printf doesn’t obviously have i as matching argument for the format string “%d”.
So, the program is incorrect and you can reasonably expect the program to print some garbage
value. But note that it is equally possible that you might get 10 as output. Why? To understand
this, let us see how compiler might transform these statements to low-level executable code.

Local variables are allocated in the stack frame of a function. When the main method is invoked,
the storage space for i is also allocated in the stack frame. A compiler should generate code to
initialize that value i with 10. The machine code will have instructions to load the value 10 in a
register and store it in the location for i in the stack frame.

The printf statement is a function call. The printf function takes a variable length argument
list. Based on the first argument – the format string – the rest of the arguments are “interpreted”.
Here the format string (“%d”) indicates that it should read the second argument and interpret it as
an integer. The printf takes variable length argument list as argument and the compiler has no
knowledge about the internal affairs of routines like printf, so, it will happily compile the code
without complaining (but a tool like Lint will warn, but that’s a different story).

The compiler generates code for invoking printf. Conventionally, a compiler would generate
code to pass the arguments in the processor registers. For Unix/Linux, the code for printf will
be in a shared library (typically named as libc). That printf code, with “%d” as argument expects
an integer to follow it. It has code to read the argument from a processor register. It happens that
most of the compilers generate code by reusing the same registers (for example, an accumulator
register in processors that are accumulator based). So, it is likely that the same register that is
used for initializing the value of i is reused for reading the argument passed to printf. So 10 it
might get printed! Yes, compilers differ considerably in ways in which they generate code, but
they are also similar in many ways in which they make use of the processor resources. So, it is not
pure coincidence if you get 10 printed even when you try different compilers (even in different
platforms).

If you are not convinced with my explanation, (1) try out this code in different platforms (by
platform, I mean a microprocessor, operating system and compiler combination) (2) take a look
at the generated assembly code by different compilers for small pieces of code like this. Even if
this program doesn’t work and print 10 in your platform, there is much to learn from this
exercise.

Now let us discuss one more aspect on local variables. If you declare some local variables, they
would typically be allocated contiguously in the stack. Try this:

int i = 0, j = 10, k = 0;
int *p = &j;
*(p - 1) = 10;
*(p + 1) = 10;
printf(quot;i = %d j = %d k = %dquot;, i, j, k);
// most compilers will print
// i = 10 j = 10 k = 10

Here we attempt to check if the local variables i, j and k are contiguously allocated by modifying
local variables i and k through a pointer p which points to the address of j. It is most likely that
you’ll get values 10 for i, j and k. But things can go wrong also; for example, compilers can do
optimizations and can decide that i and k are not modified in the program and statically replace
i and k in printf with 0’s!

S.G. Ganesh is a research engineer in Siemens (Corporate Technology). He has
authored a book “Deep C” (ISBN 81-7656-501-6). You can reach him at
sgganesh@gmail.com.

Mais conteúdo relacionado

Mais de Ganesh Samarthyam

Mais de Ganesh Samarthyam (20)

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
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
panagenda
 

Último (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
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...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

11 Jo P Nov 07

  • 1. The Joy of Programming Allocation of Local Variables in Stack It is always fun to understand the low-level details of a program and to explore how compilers work. In this column, we’ll see some details on how local variables are allocated in stack and some interesting issues on how compilers handle it. Every month, I get lots of mails and queries from LFY readers. This column seems to have become popular, particularly among students. This month, we’ll cover an interesting question from Saravanan swamy (GCT, Coimbatore). His question is: Why does the following program print 10? int i = 10; printf(“%d”); Note that the printf doesn’t obviously have i as matching argument for the format string “%d”. So, the program is incorrect and you can reasonably expect the program to print some garbage value. But note that it is equally possible that you might get 10 as output. Why? To understand this, let us see how compiler might transform these statements to low-level executable code. Local variables are allocated in the stack frame of a function. When the main method is invoked, the storage space for i is also allocated in the stack frame. A compiler should generate code to initialize that value i with 10. The machine code will have instructions to load the value 10 in a register and store it in the location for i in the stack frame. The printf statement is a function call. The printf function takes a variable length argument list. Based on the first argument – the format string – the rest of the arguments are “interpreted”. Here the format string (“%d”) indicates that it should read the second argument and interpret it as an integer. The printf takes variable length argument list as argument and the compiler has no knowledge about the internal affairs of routines like printf, so, it will happily compile the code without complaining (but a tool like Lint will warn, but that’s a different story). The compiler generates code for invoking printf. Conventionally, a compiler would generate code to pass the arguments in the processor registers. For Unix/Linux, the code for printf will be in a shared library (typically named as libc). That printf code, with “%d” as argument expects an integer to follow it. It has code to read the argument from a processor register. It happens that most of the compilers generate code by reusing the same registers (for example, an accumulator register in processors that are accumulator based). So, it is likely that the same register that is used for initializing the value of i is reused for reading the argument passed to printf. So 10 it might get printed! Yes, compilers differ considerably in ways in which they generate code, but they are also similar in many ways in which they make use of the processor resources. So, it is not pure coincidence if you get 10 printed even when you try different compilers (even in different platforms). If you are not convinced with my explanation, (1) try out this code in different platforms (by platform, I mean a microprocessor, operating system and compiler combination) (2) take a look at the generated assembly code by different compilers for small pieces of code like this. Even if this program doesn’t work and print 10 in your platform, there is much to learn from this exercise. Now let us discuss one more aspect on local variables. If you declare some local variables, they would typically be allocated contiguously in the stack. Try this: int i = 0, j = 10, k = 0; int *p = &j;
  • 2. *(p - 1) = 10; *(p + 1) = 10; printf(quot;i = %d j = %d k = %dquot;, i, j, k); // most compilers will print // i = 10 j = 10 k = 10 Here we attempt to check if the local variables i, j and k are contiguously allocated by modifying local variables i and k through a pointer p which points to the address of j. It is most likely that you’ll get values 10 for i, j and k. But things can go wrong also; for example, compilers can do optimizations and can decide that i and k are not modified in the program and statically replace i and k in printf with 0’s! S.G. Ganesh is a research engineer in Siemens (Corporate Technology). He has authored a book “Deep C” (ISBN 81-7656-501-6). You can reach him at sgganesh@gmail.com.