SlideShare a Scribd company logo
1 of 30
Download to read offline
Operating Systems
         CMPSCI 377
            C/C++
                   Emery Berger
University of Massachusetts Amherst




UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
Why C?




  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   2
Why C?
    Low-level


        Direct access to memory
    

        WYSIWYG (more or less)
    

        Effectively no runtime system
    

              No garbage collector
          

              No other threads
          

              No “read” or “write barriers”
          


    Efficient


        Space & time
    

        C: effectively portable assembly code
    


        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   3
OK, Why C++?




  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   4
OK, Why C++?
    C++: extends C


        Upwardly-compatible
    

    Adds significant software engineering


    benefits
        Classes
    

        Encapsulation (private)
    

        Templates (“generics”)
    

        Other modularity advantages
    

        Inlining instead of macros
    



        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   5
Outline, part I
    Basics – compiling & running


    Intrinsic types, conditionals, etc.


    Pointers + Reference variables


        Assignment
    

        Objects
    

        &, *, ->
    

    Stack vs. heap





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   6
Outline, part II
    Functions


        Parameter passing
    

    Structs & classes


    Overloading & inheritance


    Stack vs. heap


    I/O, command-line


    STL





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   7
Basics
    Main & compilation





     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   8
Intrinsic Types
    Essentially identical





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   9
Conditionals
    Mostly the same


        C/C++: nonzero int same as true
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   10
File I/O
    Simple stream-based I/O


                                               print foo
        cout << “foo”
    

                                               read x from the console
        cin >> x
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   11
Command-line Arguments
    Again, similar to Java





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   12
Key Differences
    Differences between C/C++ and Java


        Assignment
    

        Pointers
    

        Parameter passing
    

        Heap & Stack
    

        Arrays
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   13
Assignment
    Java assignment: makes reference


    C++ assignment: makes copy





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   14
Pointers & Friends

    Pointers are like jumps, leading wildly from


    one part of the data structure to another.
    Their introduction into high-level languages
    has been a step backwards from which we
    may never recover.
                                    C.A.R. Hoare




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   15
Pointers & Friends
    Concept not in Java: address manipulation





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   16
Functions & Parameter Passing
    C/C++ – all parameters copied by default





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   17
Parameter Passing
    To change input, pass pointer


    or call by reference




      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   18
Pass by Reference
    Syntactic sugar:


    foo (int &i) = pass by reference
        Secretly does pointer stuff for you
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   19
Stack & Heap




   UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   20
Stack & Heap
    In C/C++ as in Java, objects can live on


    stack or on heap
        Stack = region of memory for temporaries
    

              Stack pointer pushed on function entry
          

              Popped on function exit
          


        Heap = distinct region of memory for
    

        persistent objects
              C/C++ – explicitly managed
          


    Pointers introduce problems!





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   21
The Stack
    Stack data: new every time





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   22
Big Stack Mistake
    Never return pointers to the stack!





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   23
The Heap
    Allocate persistent data on heap with new





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   24
Explicit Memory Management
    Java heap – garbage collected


    C/C++ – explicit memory management


        You must delete items (or memory leak)
    




        Delete them too soon (still in use) – crash
    

              “Dangling pointer” error
          


        Delete something twice – crash
    

              “Double-free” error
          


        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   25
Classes & Objects
    No “top” object (as in Java Object)


        Also: C++ has no interfaces but has multiple
    

        inheritance – stay far away
    Key difference for you – not all methods

    dynamically-dispatched
        Methods associated with declared type
    

        rather than dynamic type unless labeled
        virtual



        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   26
Struct Member Access
    struct = class with everything public


        Use these sparingly
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   27
Class Declaration
    Pretty similar





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   28
Arrays
    Numerous differences


        Arrays do not have to be allocated with new
    

        Array bounds not checked
    

        Item[0] = pointer to start of array
    

        Arrays just syntactic sugar
    

        for pointer arithmetic! (scary! avoid!)
              v = 12; *(Item + v) = 1;
          


              Same as Item[12] = 1;
          


        Note: sizeof(x) = number of bytes to hold x
    

    Multi-dimensional arrays (matrices)


        just arrays of pointers to arrays
    
        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   29
Other Features
    Operator overloading


        New meanings to existing operators
    

              int operator+(MyType& a, MyType& b);
          


        Controversial, but useful for things like
    

        complex math, matrix operations
              int& operator()(int x, int y);
          


    Templates


        A.k.a. generics in Java
    

        template <class X> void foo (X arg);
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   30

More Related Content

Viewers also liked

Maharashtra hsc board previous year papers
Maharashtra hsc board  previous year papersMaharashtra hsc board  previous year papers
Maharashtra hsc board previous year papersHSC.co.in
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
Assembly language 8086 intermediate
Assembly language 8086 intermediateAssembly language 8086 intermediate
Assembly language 8086 intermediateJohn Cutajar
 
Bubblesort Algorithm
Bubblesort AlgorithmBubblesort Algorithm
Bubblesort AlgorithmTobias Straub
 
Bubble sort a best presentation topic
Bubble sort a best presentation topicBubble sort a best presentation topic
Bubble sort a best presentation topicSaddam Hussain
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...cprogrammings
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Laxman Puri
 
Career Option after 10+2
Career Option after 10+2Career Option after 10+2
Career Option after 10+2vishalgarodia
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sortgeeortiz
 
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMINGChapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMINGFrankie Jones
 

Viewers also liked (14)

Maharashtra hsc board previous year papers
Maharashtra hsc board  previous year papersMaharashtra hsc board  previous year papers
Maharashtra hsc board previous year papers
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Assembly language 8086 intermediate
Assembly language 8086 intermediateAssembly language 8086 intermediate
Assembly language 8086 intermediate
 
Bubblesort Algorithm
Bubblesort AlgorithmBubblesort Algorithm
Bubblesort Algorithm
 
Bubble sort a best presentation topic
Bubble sort a best presentation topicBubble sort a best presentation topic
Bubble sort a best presentation topic
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Career Option after 10+2
Career Option after 10+2Career Option after 10+2
Career Option after 10+2
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sort
 
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMINGChapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
 

Similar to Operating Systems - Intro to C++

Processes and Threads
Processes and ThreadsProcesses and Threads
Processes and ThreadsEmery Berger
 
Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing SystemsEmery Berger
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - ConcurrencyEmery Berger
 
Operating Systems - Virtual Memory
Operating Systems - Virtual MemoryOperating Systems - Virtual Memory
Operating Systems - Virtual MemoryEmery Berger
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingEmery Berger
 
Reconsidering Custom Memory Allocation
Reconsidering Custom Memory AllocationReconsidering Custom Memory Allocation
Reconsidering Custom Memory AllocationEmery Berger
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabVidhyaSenthil
 
Memory Management for High-Performance Applications
Memory Management for High-Performance ApplicationsMemory Management for High-Performance Applications
Memory Management for High-Performance ApplicationsEmery Berger
 
Reproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to ArchitectureReproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to ArchitectureJason Riedy
 
H2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt DowleH2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt DowleSri Ambati
 
Brian Oliver Pimp My Data Grid
Brian Oliver  Pimp My Data GridBrian Oliver  Pimp My Data Grid
Brian Oliver Pimp My Data Griddeimos
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationEmery Berger
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotVolha Banadyseva
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia Vladimir Ivanov
 
ICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to ArchitectureICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to ArchitectureJason Riedy
 
Reverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptReverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptYusuf Motiwala
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScriptNicholas Zakas
 

Similar to Operating Systems - Intro to C++ (20)

Processes and Threads
Processes and ThreadsProcesses and Threads
Processes and Threads
 
Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing Systems
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - Concurrency
 
Operating Systems - Virtual Memory
Operating Systems - Virtual MemoryOperating Systems - Virtual Memory
Operating Systems - Virtual Memory
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel Computing
 
Reconsidering Custom Memory Allocation
Reconsidering Custom Memory AllocationReconsidering Custom Memory Allocation
Reconsidering Custom Memory Allocation
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Simulation lab
Simulation labSimulation lab
Simulation lab
 
Memory Management for High-Performance Applications
Memory Management for High-Performance ApplicationsMemory Management for High-Performance Applications
Memory Management for High-Performance Applications
 
Reproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to ArchitectureReproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to Architecture
 
H2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt DowleH2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt Dowle
 
Brian Oliver Pimp My Data Grid
Brian Oliver  Pimp My Data GridBrian Oliver  Pimp My Data Grid
Brian Oliver Pimp My Data Grid
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced Synchronization
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
 
ICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to ArchitectureICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to Architecture
 
Reverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptReverse Engineering Malicious Javascript
Reverse Engineering Malicious Javascript
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 

More from Emery Berger

Doppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierDoppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierEmery Berger
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingEmery Berger
 
Programming with People
Programming with PeopleProgramming with People
Programming with PeopleEmery Berger
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationEmery Berger
 
DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)Emery Berger
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsEmery Berger
 
Operating Systems - File Systems
Operating Systems - File SystemsOperating Systems - File Systems
Operating Systems - File SystemsEmery Berger
 
Operating Systems - Networks
Operating Systems - NetworksOperating Systems - Networks
Operating Systems - NetworksEmery Berger
 
Operating Systems - Synchronization
Operating Systems - SynchronizationOperating Systems - Synchronization
Operating Systems - SynchronizationEmery Berger
 
Virtual Memory and Paging
Virtual Memory and PagingVirtual Memory and Paging
Virtual Memory and PagingEmery Berger
 
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsMC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsEmery Berger
 
Vam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorVam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorEmery Berger
 
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementQuantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementEmery Berger
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without PagingEmery Berger
 
DieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesDieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesEmery Berger
 
Exterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High ProbabilityExterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High ProbabilityEmery Berger
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Emery Berger
 
Composing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap LayersComposing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap LayersEmery Berger
 
CRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected ApplicationsCRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected ApplicationsEmery Berger
 

More from Emery Berger (19)

Doppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierDoppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language Barrier
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic Multithreading
 
Programming with People
Programming with PeopleProgramming with People
Programming with People
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance Evaluation
 
DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File Systems
 
Operating Systems - File Systems
Operating Systems - File SystemsOperating Systems - File Systems
Operating Systems - File Systems
 
Operating Systems - Networks
Operating Systems - NetworksOperating Systems - Networks
Operating Systems - Networks
 
Operating Systems - Synchronization
Operating Systems - SynchronizationOperating Systems - Synchronization
Operating Systems - Synchronization
 
Virtual Memory and Paging
Virtual Memory and PagingVirtual Memory and Paging
Virtual Memory and Paging
 
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsMC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
 
Vam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorVam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory Allocator
 
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementQuantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without Paging
 
DieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesDieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe Languages
 
Exterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High ProbabilityExterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High Probability
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
 
Composing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap LayersComposing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap Layers
 
CRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected ApplicationsCRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected Applications
 

Recently uploaded

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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
 
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
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Recently uploaded (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
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?
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
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
 
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
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Operating Systems - Intro to C++

  • 1. Operating Systems CMPSCI 377 C/C++ Emery Berger University of Massachusetts Amherst UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
  • 2. Why C? UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 2
  • 3. Why C? Low-level  Direct access to memory  WYSIWYG (more or less)  Effectively no runtime system  No garbage collector  No other threads  No “read” or “write barriers”  Efficient  Space & time  C: effectively portable assembly code  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 3
  • 4. OK, Why C++? UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 4
  • 5. OK, Why C++? C++: extends C  Upwardly-compatible  Adds significant software engineering  benefits Classes  Encapsulation (private)  Templates (“generics”)  Other modularity advantages  Inlining instead of macros  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 5
  • 6. Outline, part I Basics – compiling & running  Intrinsic types, conditionals, etc.  Pointers + Reference variables  Assignment  Objects  &, *, ->  Stack vs. heap  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 6
  • 7. Outline, part II Functions  Parameter passing  Structs & classes  Overloading & inheritance  Stack vs. heap  I/O, command-line  STL  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 7
  • 8. Basics Main & compilation  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 8
  • 9. Intrinsic Types Essentially identical  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 9
  • 10. Conditionals Mostly the same  C/C++: nonzero int same as true  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 10
  • 11. File I/O Simple stream-based I/O  print foo cout << “foo”  read x from the console cin >> x  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 11
  • 12. Command-line Arguments Again, similar to Java  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 12
  • 13. Key Differences Differences between C/C++ and Java  Assignment  Pointers  Parameter passing  Heap & Stack  Arrays  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 13
  • 14. Assignment Java assignment: makes reference  C++ assignment: makes copy  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 14
  • 15. Pointers & Friends Pointers are like jumps, leading wildly from  one part of the data structure to another. Their introduction into high-level languages has been a step backwards from which we may never recover. C.A.R. Hoare UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 15
  • 16. Pointers & Friends Concept not in Java: address manipulation  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 16
  • 17. Functions & Parameter Passing C/C++ – all parameters copied by default  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 17
  • 18. Parameter Passing To change input, pass pointer  or call by reference UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 18
  • 19. Pass by Reference Syntactic sugar:  foo (int &i) = pass by reference Secretly does pointer stuff for you  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 19
  • 20. Stack & Heap UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 20
  • 21. Stack & Heap In C/C++ as in Java, objects can live on  stack or on heap Stack = region of memory for temporaries  Stack pointer pushed on function entry  Popped on function exit  Heap = distinct region of memory for  persistent objects C/C++ – explicitly managed  Pointers introduce problems!  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 21
  • 22. The Stack Stack data: new every time  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 22
  • 23. Big Stack Mistake Never return pointers to the stack!  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 23
  • 24. The Heap Allocate persistent data on heap with new  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 24
  • 25. Explicit Memory Management Java heap – garbage collected  C/C++ – explicit memory management  You must delete items (or memory leak)  Delete them too soon (still in use) – crash  “Dangling pointer” error  Delete something twice – crash  “Double-free” error  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 25
  • 26. Classes & Objects No “top” object (as in Java Object)  Also: C++ has no interfaces but has multiple  inheritance – stay far away Key difference for you – not all methods  dynamically-dispatched Methods associated with declared type  rather than dynamic type unless labeled virtual UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 26
  • 27. Struct Member Access struct = class with everything public  Use these sparingly  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 27
  • 28. Class Declaration Pretty similar  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 28
  • 29. Arrays Numerous differences  Arrays do not have to be allocated with new  Array bounds not checked  Item[0] = pointer to start of array  Arrays just syntactic sugar  for pointer arithmetic! (scary! avoid!) v = 12; *(Item + v) = 1;  Same as Item[12] = 1;  Note: sizeof(x) = number of bytes to hold x  Multi-dimensional arrays (matrices)  just arrays of pointers to arrays  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 29
  • 30. Other Features Operator overloading  New meanings to existing operators  int operator+(MyType& a, MyType& b);  Controversial, but useful for things like  complex math, matrix operations int& operator()(int x, int y);  Templates  A.k.a. generics in Java  template <class X> void foo (X arg);  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 30