SlideShare a Scribd company logo
1 of 21
SPL – Practical Session 2
• Topics:
– C++ Memory Management
– Pointers
C++ Memory Handling
Memory Model, Pointers
Variables in C++ Memory System
There are two "kinds" of memory available to a process:
• Stack:
– Stores local variables of the function.
– Removed once the function ends!
• Heap:
– Contains dynamically allocated variables.
– Stays once the function ends, unless cleared before!
Read more: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
Pointers
• A pointer is a variable that holds the address of some other variable.
• In Java, you can’t directly access the memory of such object! Only by
reference.
• In C++, you can access them directly! Alter them any way you like, without any
limitations!
Benefit: More control than Java.
Drawback: Memory leaks, Memory corruption.
• A 64-bit computer can address 264 bytes!
• Each memory cell is 1 byte. (byte-accessible machines – most of the machines
today)
• Each pointer takes a static size of 4 bytes in a 32bit OS, and 8bytes in a 64bit
OS.
• Pointers themselves are saved on the stack.
Java vs. C++
Java’s References
• String s = new String("a string");
– The value of the variable 's'
is the location of the object
on the heap, but we don’t
have access to this value!
• You can not have a variable that
'points' to a primitive type
• String s = null;
– means "I don't have the
address of any meaningful
data"
C++ Pointers
• Have access to actual memory
locations.
• Can point to anything!
• The null value in C++ is the
number 0 (memory address 0).
Pointers – Bit Level
• Declaration: int x= 5
– int *ptr1 = &x;
• integers are of size 4bytes, which means:
x:
– Char c = ‘z’; char *ptr2 = &c; (‘z’ equals to 122)
• Char takes 1byte of memory:
c:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
0 1 1 1 1 0 1 0
ptr1
ptr2
Decimal to binary conversion:
http://www.wikihow.com/Convert-from-Decimal-to-Binary
ASCII table: http://www.asciitable.com/
Pointers
...
...
MEMORY ADDRESS SPACE
1000
1001
1002
1003
1004
1005
1006
81344
81345
81346
81347
Address
int x;
int *foo;
x= 123;
foo = &x;
foo
x
0
foo contains the address it points at.
*foo is the value that foo points at.
&x is the address of variable x.
&foo is the address of the pointer foo.
Comparing Pointers
• int j = 5;
• int i = 5;
• int *ptrj1 = &j;
• int *ptrj2 = &j;
• int *ptri = &i;
• True/False:
• if (ptrj1 == ptrj2) ?
• if (ptrj1 == ptri) ?
• if (&ptrj1 == &ptrj2) ?
• if (*ptrj1 == *ptri) ?
True
False
False
True
Assigning a value to a dereferenced
pointer
A pointer must have a value before you can
dereference it (follow the pointer).
int *x;
*x=3;
int foo;
int *x;
x = &foo;
*x=3;
Pointers to pointers
int *x;
int **y;
double *z;
x some int
some *int some int
y
z some double
Pointers to pointers
• Example:
– int i = 5;
– int *p_i = &i;
– int **pp_i = &p_i;
• Then:
pp_i is memory location of …
p_i
*pp_i is memory location of …
i
**pp_i equals…
5
Pointers and Arrays
• Array name is basically a const pointer
pointing at the beginning of the array.
• You can use the [] operator with pointers!
• Example:
– int A[5];
– Creates a memory block of 5 integers on the stack
(5x4bytes) where A (the pointer) points at the
beginning of the array -> A[0]. (A = &A)
A
Pointers and Arrays
int *x;
int a[5]={-1,-2,-3,-4,-5};
x = &a[2];
for (int i=0;i<3;i++)
x[i]++;
x is “the address of a[2] ”
x[i] is the same as a[i+2]
-1 -2 -3 -4 -5
a
x[0]
x[1] x[2]
x
Pointer arithmetic
• Integer math operations can be used with pointers: +, -,
++, --, +=, -=
• If you increment a pointer, it will be increased by the size
of whatever it points to.
• Incrementing pointers will basically make it point to the
“next” element in memory.
int a[5];
a[0] a[1] a[2] a[3] a[4]
int *ptr = a;
*ptr
*(ptr+2)
*(ptr+4)
C++ char*
• char* is another way to represent strings in
C++. (it actually came first - with C!)
• char* is an array of chars.
• char* arrays are terminated with ‘0’ – “null
terminated strings”. “denotes end of string”.
• char *msg= “RPI”;
• Length of string?
'R‘
msg
'P‘ 'I‘ 0
strlen(msg) == 3;
Using the Heap
• All primitives are stored in the stack,
• All that is made without new command
is stored in the stack. (except global variables and initailized char* –
splab!)
• Using the new keyword, we can now
allocate memory on the heap.
– int *i = new int;
– string *str = new string(“hi there, heap is cozy!”);
– int *arr = new int[5];
• Deleting these objects can be done
by using the delete keyword.
– delete i;
– delete str;
– delete[] arr;
Safe Delete:
if (0 != p){
delete p;
p=0;
}
DO NOT DELETE A PONTER
NOT ALLOCATED BY NEW
Pointer Pitfalls
• Assigning values to uninitialized, null, or
deleted pointers:
int *p; int *p = NULL; int *p = new int;
*p = 3; *p = 4; delete p;
*p = 5;
All of these cases end up with segmentation fault!
Dangling Pointer
• A pointer that points at nothing:
• Example:
int *p, *q;
p = new int;
q = p;
delete q;
*p = 3; //illegal assignment!
• p and q point to the same location, q is deleted, results
with p becoming a dangling pointer!
Memory Leaks
• Memory leak is when you remove the reference to the
memory block, before deleting the block itself.
Example:
int *p = new int;
p = NULL;//or a new other value
p points at memory location of type int.
p changed to point at null.
Result?
Must free memory block before changing reference.
Memory leak!
• A memory leak can diminish the performance
of the computer by reducing the amount of
available memory.
• Eventually, in the worst case, too much of the
available memory may become allocated
• and all or part of the system or devices stops
working correctly, the application fails, or the
system slows down.
Use valgrind with –leak-check=yes option if your implementation
has memory leaks.
Valgrind User Manual, The Valgrind Quick Start Guide, Graphical
User Interfaces
* This is why the –g flag is used when debugging!
• DO NOT FORGET TO SUBMIT:
– Homework0
– Homework1
– Homework2
The Targilonim help your exercise the things we
learnt so far!
• READ COURSE ANNOUNCEMETNS!
• Presentations: www.cs.bgu.ac.il/~jumanan
Before You Leave!

More Related Content

Similar to SPL_PS2 (1).ppt

FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxsangeeta borde
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C languageMehwish Mehmood
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)Dmitry Zinoviev
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedhozaifafadl
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxLECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxSKUP1
 
Lenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasLenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasJosé Luis Muñoz Meza
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
ESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptxESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptxkrishna50blogging
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
Central processing unit
Central processing unitCentral processing unit
Central processing unitHeman Pathak
 

Similar to SPL_PS2 (1).ppt (20)

Pointer
PointerPointer
Pointer
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Pointers
PointersPointers
Pointers
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
Lenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasLenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y Pandas
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
ESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptxESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptx
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
Central processing unit
Central processing unitCentral processing unit
Central processing unit
 

More from tadudemise

What is requirement gathering chap3 1.pptx
What is requirement gathering chap3 1.pptxWhat is requirement gathering chap3 1.pptx
What is requirement gathering chap3 1.pptxtadudemise
 
chaptertaaaaaaaaaaaaaaadddddddd2222 4.ppt
chaptertaaaaaaaaaaaaaaadddddddd2222 4.pptchaptertaaaaaaaaaaaaaaadddddddd2222 4.ppt
chaptertaaaaaaaaaaaaaaadddddddd2222 4.ppttadudemise
 
03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppttadudemise
 
Introduction.ppt
Introduction.pptIntroduction.ppt
Introduction.ppttadudemise
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppttadudemise
 
03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppttadudemise
 

More from tadudemise (8)

What is requirement gathering chap3 1.pptx
What is requirement gathering chap3 1.pptxWhat is requirement gathering chap3 1.pptx
What is requirement gathering chap3 1.pptx
 
chaptertaaaaaaaaaaaaaaadddddddd2222 4.ppt
chaptertaaaaaaaaaaaaaaadddddddd2222 4.pptchaptertaaaaaaaaaaaaaaadddddddd2222 4.ppt
chaptertaaaaaaaaaaaaaaadddddddd2222 4.ppt
 
8329969.ppt
8329969.ppt8329969.ppt
8329969.ppt
 
03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt
 
Introduction.ppt
Introduction.pptIntroduction.ppt
Introduction.ppt
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppt
 
03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt03a-IntroductionToEventDrivenProgramming.ppt
03a-IntroductionToEventDrivenProgramming.ppt
 

Recently uploaded

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

SPL_PS2 (1).ppt

  • 1. SPL – Practical Session 2 • Topics: – C++ Memory Management – Pointers
  • 2. C++ Memory Handling Memory Model, Pointers
  • 3. Variables in C++ Memory System There are two "kinds" of memory available to a process: • Stack: – Stores local variables of the function. – Removed once the function ends! • Heap: – Contains dynamically allocated variables. – Stays once the function ends, unless cleared before! Read more: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
  • 4. Pointers • A pointer is a variable that holds the address of some other variable. • In Java, you can’t directly access the memory of such object! Only by reference. • In C++, you can access them directly! Alter them any way you like, without any limitations! Benefit: More control than Java. Drawback: Memory leaks, Memory corruption. • A 64-bit computer can address 264 bytes! • Each memory cell is 1 byte. (byte-accessible machines – most of the machines today) • Each pointer takes a static size of 4 bytes in a 32bit OS, and 8bytes in a 64bit OS. • Pointers themselves are saved on the stack.
  • 5. Java vs. C++ Java’s References • String s = new String("a string"); – The value of the variable 's' is the location of the object on the heap, but we don’t have access to this value! • You can not have a variable that 'points' to a primitive type • String s = null; – means "I don't have the address of any meaningful data" C++ Pointers • Have access to actual memory locations. • Can point to anything! • The null value in C++ is the number 0 (memory address 0).
  • 6. Pointers – Bit Level • Declaration: int x= 5 – int *ptr1 = &x; • integers are of size 4bytes, which means: x: – Char c = ‘z’; char *ptr2 = &c; (‘z’ equals to 122) • Char takes 1byte of memory: c: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 1 0 1 0 ptr1 ptr2 Decimal to binary conversion: http://www.wikihow.com/Convert-from-Decimal-to-Binary ASCII table: http://www.asciitable.com/
  • 7. Pointers ... ... MEMORY ADDRESS SPACE 1000 1001 1002 1003 1004 1005 1006 81344 81345 81346 81347 Address int x; int *foo; x= 123; foo = &x; foo x 0 foo contains the address it points at. *foo is the value that foo points at. &x is the address of variable x. &foo is the address of the pointer foo.
  • 8. Comparing Pointers • int j = 5; • int i = 5; • int *ptrj1 = &j; • int *ptrj2 = &j; • int *ptri = &i; • True/False: • if (ptrj1 == ptrj2) ? • if (ptrj1 == ptri) ? • if (&ptrj1 == &ptrj2) ? • if (*ptrj1 == *ptri) ? True False False True
  • 9. Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; int foo; int *x; x = &foo; *x=3;
  • 10. Pointers to pointers int *x; int **y; double *z; x some int some *int some int y z some double
  • 11. Pointers to pointers • Example: – int i = 5; – int *p_i = &i; – int **pp_i = &p_i; • Then: pp_i is memory location of … p_i *pp_i is memory location of … i **pp_i equals… 5
  • 12. Pointers and Arrays • Array name is basically a const pointer pointing at the beginning of the array. • You can use the [] operator with pointers! • Example: – int A[5]; – Creates a memory block of 5 integers on the stack (5x4bytes) where A (the pointer) points at the beginning of the array -> A[0]. (A = &A) A
  • 13. Pointers and Arrays int *x; int a[5]={-1,-2,-3,-4,-5}; x = &a[2]; for (int i=0;i<3;i++) x[i]++; x is “the address of a[2] ” x[i] is the same as a[i+2] -1 -2 -3 -4 -5 a x[0] x[1] x[2] x
  • 14. Pointer arithmetic • Integer math operations can be used with pointers: +, -, ++, --, +=, -= • If you increment a pointer, it will be increased by the size of whatever it points to. • Incrementing pointers will basically make it point to the “next” element in memory. int a[5]; a[0] a[1] a[2] a[3] a[4] int *ptr = a; *ptr *(ptr+2) *(ptr+4)
  • 15. C++ char* • char* is another way to represent strings in C++. (it actually came first - with C!) • char* is an array of chars. • char* arrays are terminated with ‘0’ – “null terminated strings”. “denotes end of string”. • char *msg= “RPI”; • Length of string? 'R‘ msg 'P‘ 'I‘ 0 strlen(msg) == 3;
  • 16. Using the Heap • All primitives are stored in the stack, • All that is made without new command is stored in the stack. (except global variables and initailized char* – splab!) • Using the new keyword, we can now allocate memory on the heap. – int *i = new int; – string *str = new string(“hi there, heap is cozy!”); – int *arr = new int[5]; • Deleting these objects can be done by using the delete keyword. – delete i; – delete str; – delete[] arr; Safe Delete: if (0 != p){ delete p; p=0; } DO NOT DELETE A PONTER NOT ALLOCATED BY NEW
  • 17. Pointer Pitfalls • Assigning values to uninitialized, null, or deleted pointers: int *p; int *p = NULL; int *p = new int; *p = 3; *p = 4; delete p; *p = 5; All of these cases end up with segmentation fault!
  • 18. Dangling Pointer • A pointer that points at nothing: • Example: int *p, *q; p = new int; q = p; delete q; *p = 3; //illegal assignment! • p and q point to the same location, q is deleted, results with p becoming a dangling pointer!
  • 19. Memory Leaks • Memory leak is when you remove the reference to the memory block, before deleting the block itself. Example: int *p = new int; p = NULL;//or a new other value p points at memory location of type int. p changed to point at null. Result? Must free memory block before changing reference. Memory leak!
  • 20. • A memory leak can diminish the performance of the computer by reducing the amount of available memory. • Eventually, in the worst case, too much of the available memory may become allocated • and all or part of the system or devices stops working correctly, the application fails, or the system slows down. Use valgrind with –leak-check=yes option if your implementation has memory leaks. Valgrind User Manual, The Valgrind Quick Start Guide, Graphical User Interfaces * This is why the –g flag is used when debugging!
  • 21. • DO NOT FORGET TO SUBMIT: – Homework0 – Homework1 – Homework2 The Targilonim help your exercise the things we learnt so far! • READ COURSE ANNOUNCEMETNS! • Presentations: www.cs.bgu.ac.il/~jumanan Before You Leave!