SlideShare a Scribd company logo
1 of 19
Download to read offline
A Crash Course in C
GDSC Reading Week Workshop 3
Admin Stuff
- A CSC209 disclaimer
- Getting the demo code
- SSH into the DH2020 Lab machines using the Remote-SSH VSCode extension
- Open terminal (Ctrl + `) in VSCode, and run:
- git clone https://github.com/utmgdsc/2023-c-workshop
- This should download the GitHub repository, and you should have access to the
files
What is C?
- A statically-typed, compiled programming language
- Developed by Ken Thompson and Dennis Ritchie for UNIX
The Impact of C
- Implementation language of numerous software tools
- All modern operating systems (Linux, Windows, MacOS)
- The Python interpreter
- Java Virtual Machine
- Anything low-level, really
- Influenced numerous other programming languages
Python vs. C
Python
- Runtime:
- Interpreted
- Type System:
- Dynamic, strong
- Paradigm:
- Object-oriented, functional
- Easy to use, beginner-friendly
- Sloooooow
C
- Runtime:
- Compiled
- Type System:
- Static, weak
- Paradigm:
- Structural/Imperative
- Difficult to master, memory
management is a pain
- Blazing fast
Anatomy of a C Program
Import Statement
Entry Point
Declaration
Return Value
Return Statement
Print Statement
Control Flow and Data Types
- Conditional Statements
- If-Else, Switch-Case
- Loops
- For and While Loops
- Function Calls
- Type Casting
- Various Flavors of Integers
- Int, unsigned int, long, long long
- Floats and Doubles
- Char (characters)
- Booleans (with a caveat!)
- Arrays
- Structs (create your own type!)
- Pointers
- Strings…?
C is a very simple language,
but very hard to master!
Pointers: A Motivating Example
How many bytes do data types use?
- Integers
- Default 4 bytes (32 bits), longs are 8 bytes (64 bits)
- Characters
- Always 1 byte (8 bits)
- Booleans
- Always 1 byte
- Arrays
- However big the programmer declares them to be
- Size is known at compile time
How Big is a String?
- “Hello World!” has 12 characters, so 12 bytes
- “I like Dan Zingaro’s cows” has 25 characters, so 25 bytes
- A string can be 1 byte, 20 bytes, 420 bytes, 32,000 bytes…
We don’t know how big a string is!
(Rather, strings have arbitrary size that is not always known at compile time)
Pointers (for real this time)
- Stores the memory address of an object
- Rather than the object itself
- “Points” to the object
- Closest analogue: object IDs in Python
- Pointers are 4 bytes (32 bits) or 8 bytes (64 bits), depending on the system
- Indicated by an asterisk * in C
- e.g. int *c declares a pointer (named c) pointing to an integer
- Pointer operators
- ‘&’ (The reference operator)
- ‘*’ (The dereference operator)
- How strings are stored in C!
- char *, or char[]
Strings in Memory
H E L L O ! 0
0x45f24a 0x45f24b 0x45f24c 0x45f24d 0x45f24e 0x45f24f 0x45f250
char *string
C’s Memory Model
The Stack (a.k.a the call stack)
- Most sized variables live here
- Integers
- Pointers
- Predefined arrays
- Etc etc.
- Most items get allocated and
deallocated automatically when a
function returns
- Size of stack variables cannot be
changed
The Heap
- Used for storing variables of
unknown size
- e.g. strings
- Size of heap variables can be
changed
- Always interacted with through
pointers
- Must be managed manually by the
programmer
- The reason why memory
management is so important!
Memory Management
Memory Allocation (malloc)
- Allocates a block of memory on the heap
- Returns a pointer to the allocated block
- Takes one argument specifying how
many bytes the programmer wants
- Comes in various flavors:
- calloc - zeroes out the memory before
being used
- realloc - resizes an existing block of
memory
- If allocation fails, returns NULL
Memory Deallocation (free)
- Deallocates the memory being
pointed to by a given pointer and
frees it up for other use
- Takes one argument, a pointer that
points to the block of memory to be
deallocated
- The block to be deallocated must
have been previously allocated, if not
bad things happen!
Memory Management Best Practices
- The GOLDEN RULE of Memory
Management:
- Anything allocated must always be
freed after use.
- For every malloc there must exist
one (and only one) free!
- Avoid aliasing
- Avoid dangling pointers
- Any dangling pointers should be set
to NULL
- Watch out for out-of-bounds errors!
What can go wrong?
- Segfaults
- Out-of-bounds errors
- Use-after-free
- Usually results from aliasing
- Buffer Overflow
- Usually from writing to memory that
is not allocated
- Security Vulnerabilities!
Structs and Typedefs
Structs
- Allow programmers to create custom
data types
- Provide ways of grouping related
data under a single name
- This is done by defining fields within
a struct
Typedefs
- Allow programmers to create type
aliases for existing types
- Can be used to redefine existing
types to a more relevant name, or
define a struct to use more succinct
syntax
Pointers and Structs
- Pointers are often used with structs
- C is a pass-by-value language, so pointers allow pass-by-reference
- Common syntax includes:
- struct some_struct *var_name;
- typedef struct somestruct *structptr;
- structptr ptr = malloc(sizeof(some_struct));
- Same memory management rules apply!
Putting It All Together
A Linked List!
- What we will implement:
- Append
- Push
- Remove
- Index
Homework!
- Figure out recursion
- Implement linked list operations recursively
- Implement a recursive fibonacci number calculator
- Implement a dynamic string read function
- Implement a binary search tree
- Implement one of your existing (smaller) projects in C
- Do some reading
- History of C and UNIX
- How a C program is compiled
- How malloc and free work
- “The C Programming Language” by Brian Kernighan
Thank You!
Any Questions?

More Related Content

Similar to Basics of C

Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP PerspectiveBarry Jones
 
Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Peter Hlavaty
 
Script of Scripts Polyglot Notebook and Workflow System
Script of ScriptsPolyglot Notebook and Workflow SystemScript of ScriptsPolyglot Notebook and Workflow System
Script of Scripts Polyglot Notebook and Workflow SystemBo Peng
 
6-9-2017-slides-vFinal.pptx
6-9-2017-slides-vFinal.pptx6-9-2017-slides-vFinal.pptx
6-9-2017-slides-vFinal.pptxSimRelokasi2
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptvinu28455
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010Clay Helberg
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
A Comparison of .NET Framework vs. Java Virtual Machine
A Comparison of .NET Framework vs. Java Virtual MachineA Comparison of .NET Framework vs. Java Virtual Machine
A Comparison of .NET Framework vs. Java Virtual MachineAbdelrahman Hosny
 
General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming ConceptHaris Bin Zahid
 
Scale11x lxc talk
Scale11x lxc talkScale11x lxc talk
Scale11x lxc talkdotCloud
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarMaarten Balliauw
 
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...RootedCON
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_iNico Ludwig
 

Similar to Basics of C (20)

Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Intro reverse engineering
Intro reverse engineeringIntro reverse engineering
Intro reverse engineering
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Memory models in c#
Memory models in c#Memory models in c#
Memory models in c#
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!
 
Script of Scripts Polyglot Notebook and Workflow System
Script of ScriptsPolyglot Notebook and Workflow SystemScript of ScriptsPolyglot Notebook and Workflow System
Script of Scripts Polyglot Notebook and Workflow System
 
6-9-2017-slides-vFinal.pptx
6-9-2017-slides-vFinal.pptx6-9-2017-slides-vFinal.pptx
6-9-2017-slides-vFinal.pptx
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 
A Comparison of .NET Framework vs. Java Virtual Machine
A Comparison of .NET Framework vs. Java Virtual MachineA Comparison of .NET Framework vs. Java Virtual Machine
A Comparison of .NET Framework vs. Java Virtual Machine
 
General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming Concept
 
Scale11x lxc talk
Scale11x lxc talkScale11x lxc talk
Scale11x lxc talk
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...
Sergi Álvarez + Roi Martín - radare2: From forensics to bindiffing [RootedCON...
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
Modern C++
Modern C++Modern C++
Modern C++
 

More from GDSC UofT Mississauga

ICCIT Council × GDSC: UX / UI and Figma
ICCIT Council × GDSC: UX / UI and FigmaICCIT Council × GDSC: UX / UI and Figma
ICCIT Council × GDSC: UX / UI and FigmaGDSC UofT Mississauga
 
Community Projects Info Session Fall 2023
Community Projects Info Session Fall 2023Community Projects Info Session Fall 2023
Community Projects Info Session Fall 2023GDSC UofT Mississauga
 
MCSS × GDSC: Intro to Cybersecurity Workshop
MCSS × GDSC: Intro to Cybersecurity WorkshopMCSS × GDSC: Intro to Cybersecurity Workshop
MCSS × GDSC: Intro to Cybersecurity WorkshopGDSC UofT Mississauga
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 

More from GDSC UofT Mississauga (20)

CSSC ML Workshop
CSSC ML WorkshopCSSC ML Workshop
CSSC ML Workshop
 
ICCIT Council × GDSC: UX / UI and Figma
ICCIT Council × GDSC: UX / UI and FigmaICCIT Council × GDSC: UX / UI and Figma
ICCIT Council × GDSC: UX / UI and Figma
 
Community Projects Info Session Fall 2023
Community Projects Info Session Fall 2023Community Projects Info Session Fall 2023
Community Projects Info Session Fall 2023
 
GDSC x Deerhacks - Origami Workshop
GDSC x Deerhacks - Origami WorkshopGDSC x Deerhacks - Origami Workshop
GDSC x Deerhacks - Origami Workshop
 
Reverse Engineering 101
Reverse Engineering 101Reverse Engineering 101
Reverse Engineering 101
 
Michael's OWASP Juice Shop Workshop
Michael's OWASP Juice Shop WorkshopMichael's OWASP Juice Shop Workshop
Michael's OWASP Juice Shop Workshop
 
MCSS × GDSC: Intro to Cybersecurity Workshop
MCSS × GDSC: Intro to Cybersecurity WorkshopMCSS × GDSC: Intro to Cybersecurity Workshop
MCSS × GDSC: Intro to Cybersecurity Workshop
 
Discord Bot Workshop Slides
Discord Bot Workshop SlidesDiscord Bot Workshop Slides
Discord Bot Workshop Slides
 
Web Scraping Workshop
Web Scraping WorkshopWeb Scraping Workshop
Web Scraping Workshop
 
Devops Workshop
Devops WorkshopDevops Workshop
Devops Workshop
 
Express
ExpressExpress
Express
 
HTML_CSS_JS Workshop
HTML_CSS_JS WorkshopHTML_CSS_JS Workshop
HTML_CSS_JS Workshop
 
DevOps Workshop Part 1
DevOps Workshop Part 1DevOps Workshop Part 1
DevOps Workshop Part 1
 
Docker workshop GDSC_CSSC
Docker workshop GDSC_CSSCDocker workshop GDSC_CSSC
Docker workshop GDSC_CSSC
 
Back-end (Flask_AWS)
Back-end (Flask_AWS)Back-end (Flask_AWS)
Back-end (Flask_AWS)
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Git Init (Introduction to Git)
Git Init (Introduction to Git)Git Init (Introduction to Git)
Git Init (Introduction to Git)
 
Database Workshop Slides
Database Workshop SlidesDatabase Workshop Slides
Database Workshop Slides
 
ChatGPT General Meeting
ChatGPT General MeetingChatGPT General Meeting
ChatGPT General Meeting
 
Elon & Twitter General Meeting
Elon & Twitter General MeetingElon & Twitter General Meeting
Elon & Twitter General Meeting
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Basics of C

  • 1. A Crash Course in C GDSC Reading Week Workshop 3
  • 2. Admin Stuff - A CSC209 disclaimer - Getting the demo code - SSH into the DH2020 Lab machines using the Remote-SSH VSCode extension - Open terminal (Ctrl + `) in VSCode, and run: - git clone https://github.com/utmgdsc/2023-c-workshop - This should download the GitHub repository, and you should have access to the files
  • 3. What is C? - A statically-typed, compiled programming language - Developed by Ken Thompson and Dennis Ritchie for UNIX
  • 4. The Impact of C - Implementation language of numerous software tools - All modern operating systems (Linux, Windows, MacOS) - The Python interpreter - Java Virtual Machine - Anything low-level, really - Influenced numerous other programming languages
  • 5. Python vs. C Python - Runtime: - Interpreted - Type System: - Dynamic, strong - Paradigm: - Object-oriented, functional - Easy to use, beginner-friendly - Sloooooow C - Runtime: - Compiled - Type System: - Static, weak - Paradigm: - Structural/Imperative - Difficult to master, memory management is a pain - Blazing fast
  • 6. Anatomy of a C Program Import Statement Entry Point Declaration Return Value Return Statement Print Statement
  • 7. Control Flow and Data Types - Conditional Statements - If-Else, Switch-Case - Loops - For and While Loops - Function Calls - Type Casting - Various Flavors of Integers - Int, unsigned int, long, long long - Floats and Doubles - Char (characters) - Booleans (with a caveat!) - Arrays - Structs (create your own type!) - Pointers - Strings…? C is a very simple language, but very hard to master!
  • 8. Pointers: A Motivating Example How many bytes do data types use? - Integers - Default 4 bytes (32 bits), longs are 8 bytes (64 bits) - Characters - Always 1 byte (8 bits) - Booleans - Always 1 byte - Arrays - However big the programmer declares them to be - Size is known at compile time
  • 9. How Big is a String? - “Hello World!” has 12 characters, so 12 bytes - “I like Dan Zingaro’s cows” has 25 characters, so 25 bytes - A string can be 1 byte, 20 bytes, 420 bytes, 32,000 bytes… We don’t know how big a string is! (Rather, strings have arbitrary size that is not always known at compile time)
  • 10. Pointers (for real this time) - Stores the memory address of an object - Rather than the object itself - “Points” to the object - Closest analogue: object IDs in Python - Pointers are 4 bytes (32 bits) or 8 bytes (64 bits), depending on the system - Indicated by an asterisk * in C - e.g. int *c declares a pointer (named c) pointing to an integer - Pointer operators - ‘&’ (The reference operator) - ‘*’ (The dereference operator) - How strings are stored in C! - char *, or char[]
  • 11. Strings in Memory H E L L O ! 0 0x45f24a 0x45f24b 0x45f24c 0x45f24d 0x45f24e 0x45f24f 0x45f250 char *string
  • 12. C’s Memory Model The Stack (a.k.a the call stack) - Most sized variables live here - Integers - Pointers - Predefined arrays - Etc etc. - Most items get allocated and deallocated automatically when a function returns - Size of stack variables cannot be changed The Heap - Used for storing variables of unknown size - e.g. strings - Size of heap variables can be changed - Always interacted with through pointers - Must be managed manually by the programmer - The reason why memory management is so important!
  • 13. Memory Management Memory Allocation (malloc) - Allocates a block of memory on the heap - Returns a pointer to the allocated block - Takes one argument specifying how many bytes the programmer wants - Comes in various flavors: - calloc - zeroes out the memory before being used - realloc - resizes an existing block of memory - If allocation fails, returns NULL Memory Deallocation (free) - Deallocates the memory being pointed to by a given pointer and frees it up for other use - Takes one argument, a pointer that points to the block of memory to be deallocated - The block to be deallocated must have been previously allocated, if not bad things happen!
  • 14. Memory Management Best Practices - The GOLDEN RULE of Memory Management: - Anything allocated must always be freed after use. - For every malloc there must exist one (and only one) free! - Avoid aliasing - Avoid dangling pointers - Any dangling pointers should be set to NULL - Watch out for out-of-bounds errors! What can go wrong? - Segfaults - Out-of-bounds errors - Use-after-free - Usually results from aliasing - Buffer Overflow - Usually from writing to memory that is not allocated - Security Vulnerabilities!
  • 15. Structs and Typedefs Structs - Allow programmers to create custom data types - Provide ways of grouping related data under a single name - This is done by defining fields within a struct Typedefs - Allow programmers to create type aliases for existing types - Can be used to redefine existing types to a more relevant name, or define a struct to use more succinct syntax
  • 16. Pointers and Structs - Pointers are often used with structs - C is a pass-by-value language, so pointers allow pass-by-reference - Common syntax includes: - struct some_struct *var_name; - typedef struct somestruct *structptr; - structptr ptr = malloc(sizeof(some_struct)); - Same memory management rules apply!
  • 17. Putting It All Together A Linked List! - What we will implement: - Append - Push - Remove - Index
  • 18. Homework! - Figure out recursion - Implement linked list operations recursively - Implement a recursive fibonacci number calculator - Implement a dynamic string read function - Implement a binary search tree - Implement one of your existing (smaller) projects in C - Do some reading - History of C and UNIX - How a C program is compiled - How malloc and free work - “The C Programming Language” by Brian Kernighan