SlideShare ist ein Scribd-Unternehmen logo
1 von 1
Downloaden Sie, um offline zu lesen
The Joy of
Programming
Allocation of Local Variables in Stack
                                                                                                                  S.G. GANESH
It is always fun to understand the low-level details of a program and to explore
how compilers work. In this column, we’ll look at some details on how local
variables are allocated in stack and some interesting issues on how compilers
handle it.

             very month, I get lots of mails and queries from       example, an accumulator register in processors that are




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


124   NOVEMBER 2007   |   LINUX FOR YOU    |   www.linuxforu.com



                                                                   CMYK

Weitere ähnliche Inhalte

Was ist angesagt?

Python Training Topics
Python Training TopicsPython Training Topics
Python Training Topicsvibrantuser
 
What every beginning developer should know
What every beginning developer should knowWhat every beginning developer should know
What every beginning developer should knowAndy Lester
 
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...SANTIAGO PABLO ALBERTO
 
Compiler Design File
Compiler Design FileCompiler Design File
Compiler Design FileArchita Misra
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014Phillip Trelford
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
First program of C ( Complete Explanation )
First program of C ( Complete Explanation )First program of C ( Complete Explanation )
First program of C ( Complete Explanation )Rohit Singh
 
Introduction to C++,Computer Science
Introduction to C++,Computer ScienceIntroduction to C++,Computer Science
Introduction to C++,Computer ScienceAbhinav Vishnoi
 

Was ist angesagt? (14)

Python Training Topics
Python Training TopicsPython Training Topics
Python Training Topics
 
What every beginning developer should know
What every beginning developer should knowWhat every beginning developer should know
What every beginning developer should know
 
First session quiz
First session quizFirst session quiz
First session quiz
 
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
 
Compiler Design File
Compiler Design FileCompiler Design File
Compiler Design File
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Java programlist (1)
Java programlist (1)Java programlist (1)
Java programlist (1)
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
First program of C ( Complete Explanation )
First program of C ( Complete Explanation )First program of C ( Complete Explanation )
First program of C ( Complete Explanation )
 
Python programming
Python programmingPython programming
Python programming
 
Introduction to C++,Computer Science
Introduction to C++,Computer ScienceIntroduction to C++,Computer Science
Introduction to C++,Computer Science
 
Unsafe
UnsafeUnsafe
Unsafe
 

Andere mochten auch (8)

Starting The Bloggg
Starting The BlogggStarting The Bloggg
Starting The Bloggg
 
Namenlint Horizontaal
Namenlint HorizontaalNamenlint Horizontaal
Namenlint Horizontaal
 
Sparing the Rod and Nurturing the Child : Caribbean culture and violence agai...
Sparing the Rod and Nurturing the Child : Caribbean culture and violence agai...Sparing the Rod and Nurturing the Child : Caribbean culture and violence agai...
Sparing the Rod and Nurturing the Child : Caribbean culture and violence agai...
 
Flame Academy Suzi Yaraei
Flame Academy Suzi YaraeiFlame Academy Suzi Yaraei
Flame Academy Suzi Yaraei
 
Fact Sheet: Youth with Disabilities
Fact Sheet: Youth with DisabilitiesFact Sheet: Youth with Disabilities
Fact Sheet: Youth with Disabilities
 
The project of meridian
The project of meridianThe project of meridian
The project of meridian
 
EvaluacióN De Adhesivos
EvaluacióN De AdhesivosEvaluacióN De Adhesivos
EvaluacióN De Adhesivos
 
2011 - Outcome document of the High-level Meeting of the General Assembly on ...
2011 - Outcome document of the High-level Meeting of the General Assembly on ...2011 - Outcome document of the High-level Meeting of the General Assembly on ...
2011 - Outcome document of the High-level Meeting of the General Assembly on ...
 

Ähnlich wie 10 Jo P Oct 07 (20)

How a Compiler Works ?
How a Compiler Works ?How a Compiler Works ?
How a Compiler Works ?
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Mark asoi ppt
Mark asoi pptMark asoi ppt
Mark asoi ppt
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
12 Jo P Dec 07
12 Jo P Dec 0712 Jo P Dec 07
12 Jo P Dec 07
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Tutorial
TutorialTutorial
Tutorial
 
My final requirement
My final requirementMy final requirement
My final requirement
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
14 Jo P Feb 08
14 Jo P Feb 0814 Jo P Feb 08
14 Jo P Feb 08
 
4 coding from algorithms
4 coding from algorithms4 coding from algorithms
4 coding from algorithms
 
Java
JavaJava
Java
 
Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Writing Efficient Code Feb 08
Writing Efficient Code Feb 08
 
Basic c
Basic cBasic c
Basic c
 
Essential c
Essential cEssential c
Essential c
 
Essential c notes singh projects
Essential c notes singh projectsEssential c notes singh projects
Essential c notes singh projects
 
Essential c
Essential cEssential c
Essential c
 
Essential c
Essential cEssential c
Essential c
 
Essential c
Essential cEssential c
Essential c
 

Mehr von Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
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”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
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 ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
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)Ganesh Samarthyam
 
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++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
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 LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
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 quizGanesh Samarthyam
 

Mehr von Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
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
 

Kürzlich hochgeladen

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
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
 
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
 
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
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
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
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Kürzlich hochgeladen (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
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
 
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
 
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
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
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
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
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?
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

10 Jo P Oct 07

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