SlideShare uma empresa Scribd logo
1 de 1
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque (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 ...
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
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
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
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
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 

Último (20)

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
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
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
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.
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
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
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 

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