SlideShare a Scribd company logo
1 of 11
ESC101: Fundamentals of Computing
Pointers and Memory Allocation
Nisheeth
ESC101: Fundamentals of
Computing
Pointers
A pointer refers to an address in memory (2^64 – 1 possible addresses)
Syntax for declaration: type *ptr; // ptr is pointer to a variable with data
type “type” (examples: int *ptr, char *ptr)
Can declare pointer and regular variables on same line
Dereferencing a pointer gives the value stored at that address
Dereferencing is done using * operator
If ptr is a pointer to a variable i then *ptr means i
For arrays, the name itself is the pointer and points to first element
char a, b, *x, *y;
x = &a, y = &b;
int a, b, *x, *y;
x = &a, y = &b;
float a, b, *x, *y;
x = &a, y = &b;
The pointer itself takes
8 bytes in memory
ESC101: Fundamentals of
Computing
Operator Name Symbol/Sign Associativity
Brackets (array subscript), Post
increment/decrement
(), [] ++, -- Left
Unary negation, Pre-
increment/decrement, NOT,
(de)reference, sizeof
-, ++, --, !, *, &,
sizeof
Right
Multiplication/division/ remainder *, /, % Left
Addition/subtraction +, - Left
Relational <, <=, >, >= Left
Relational ==, != Left
AND && Left
OR || Left
Ternary Conditional ? : Right
Assignment, Compound
assignment
=, +=, -=, *=, /=,
%=
Right
HIGH
PRECEDENCE
LOW
PRECEDENCE
Be careful, * can act as
multiplication operator as
well as dereference operator
int a = 10;
int *ptr = &a;
printf("%d", 3**ptr);
30
ESC101: Fundamentals of
Computing
Pointer Arithmetic
Can take a pointer variable add and subtract integers
Result depends on the type of the pointer
Pointers to int advance by 4 upon adding 1 or doing ++
Pointers to int go back by 4 upon subtracting 1 or doing --
Pointers to char advance by 1 upon adding 1 or doing ++
Pointers to char go back by 1 upon subtracting 1 or doing --
Pointers to double advance by 8 upon adding 1 or doing ++
Pointers to double go back by 8 upon subtracting 1 or doing --
Note: Can’t increment/decrement an array pointer (more on this
later)
ESC101: Fundamentals of
Computing
Pointers and Arrays
Array names are pointers to first element of the array
Warning: consecutive addresses only assured in arrays
a, b need not be placed side-by-side (i.e. 4 bytes apart) but arr[0], arr[1]
will always be 4 bytes apart (int takes 4 bytes)
Pointer arithmetic often used to traverse (go back and forth in)
arrays and calculate offsets
and both give value of the 3rd element in arr
Warning: arr++ will give error, ptr++ will move pointer to arr[1]
int arr[10]
int a, b, *ptr = arr;
arr[2] *(arr+2)
The array name will always
point to the first element of the
array. Cannot change that!
To do fancy pointer arithmetic,
we should create a fresh
pointer variable e.g. ptr
ESC101: Fundamentals of
Computing
Pointers and Arrays
a a[0] a[1] a[2] a[3] a[4] a[5]
22 55
000023
000023
000027 000031 000035 000039 000043
11 33 44 66
int a[6] = {11,22,33,44,55,66};
int *ptr = a;
ptr 000023
ptr += 2;
*ptr += 2;
35
printf("%d",ptr-a);
2
But the address
difference is 31-23 = 8
Yes, but since this
is int type, I treat
4 bytes as a unit
Mr C also disallows
subtraction of pointers
of different types
Yes, I will give an error
if you, for e.g. subtract
char* from int*
000031
If we really want to
subtract a char* from
int*, do a typecast!
ESC101: Fundamentals of
Computing
Pointers and Strings
Pointers are invaluable in managing strings
Most library functions we use for strings (printf, scanf, strlen,
strcat, strstr, strchr) operate with pointers
Really do not care whether the pointer is to beginning of the
string or in the middle of the string
Start processing from the location given pointer “points” 
char mind[] = "blown";
char str[] = "Hello World";
char *ptr = str;
printf("%sn%s", str, ++ptr);
Hello World
ello World
ESC101: Fundamentals of
Computing
Variable-length arrays
So far we have always used arrays with constant length
Waste of space – often allocate much more to be “safe”
Also need to remember how much of array actually used
Rest of the array may be filled with junk (not always zeros)
In strings NULL character does this job
For other types of arrays, need to do this ourselves 
Lets us learn ways for on-demand memory allocation
The secret behind getline and other modern functions
Need to include stdlib.h for these functions
malloc(), calloc(), realloc(), free()
int c[10];
ESC101: Fundamentals of
Computing
malloc – memory allocation
We tell malloc how many bytes are required
malloc allocates those many consecutive bytes
Returns the address of (a pointer to) the first byte
Warning: allocated bytes filled with garbage
Warning: if insufficient memory, NULL pointer returned
malloc has no idea if we are allocating an array of floats or
chars – returns a void* pointer – typecast it yourself
The allocated memory can be used safely as an array
See example in accompanying code
ESC101: Fundamentals of
Computing
calloc – contiguous allocation
A helpful version of malloc that initializes memory to 0 
However, slower than malloc since time spent initializing
Use this if you actually want zero initialization
Syntax a bit different – instead of total number of bytes, we need
to send it two things
length of array (number of elements in the array)
number of bytes per element
Sends back a NULL pointer if insufficient memory – careful!
Need to typecast the pointer returned by calloc too!
See example in accompanying code
ESC101: Fundamentals of
Computing
realloc – revised allocation
If you malloc-ed an array of 100 elements and suddenly find that
you need an array of 200 elements 
Can use realloc to revise that allocation to 200 elements
Don’t use realloc to increase size of non-malloc arrays
Use realloc only to increase size of calloc/malloc-ed arrays
int *ptr = (int*)malloc(100 * sizeof(int));
I realize that. That is why I will
copy those 100 elements to the
new array of 200 elements 
int *tmp = (int*)realloc(ptr, 200 * sizeof(int));
if(tmp != NULL) ptr = tmp;
But what if I had
precious data stored
in those 100 elements
You are the best Mr C
int c[100];
int *ptr = (int*)realloc(c, 200 * sizeof(int)); // Runtime error
I will also free the old 100
elements – you don’t have
to write free() for them

More Related Content

Similar to ESC112 Course lecture slides on pointers and memory allocation.pptx

03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.pptArifKamal36
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.pptsuriyakalavinoth
 
03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt03-arrays-pointers (1).ppt
03-arrays-pointers (1).pptSyedaNooreen
 
arrays, pointers and operations pointers
arrays, pointers and operations pointersarrays, pointers and operations pointers
arrays, pointers and operations pointersShalabhMishra10
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
c-arrays-pointers.ppt
c-arrays-pointers.pptc-arrays-pointers.ppt
c-arrays-pointers.pptDEEPAK948083
 
c-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzzc-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzzSiliconVeli
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it outrajatryadav22
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxAbhimanyuChaure
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
009 Data Handling .pptx
009 Data Handling .pptx009 Data Handling .pptx
009 Data Handling .pptxssuser6c66f3
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 

Similar to ESC112 Course lecture slides on pointers and memory allocation.pptx (20)

Lecture 9
Lecture 9Lecture 9
Lecture 9
 
03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.ppt
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt
 
03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt
 
arrays, pointers and operations pointers
arrays, pointers and operations pointersarrays, pointers and operations pointers
arrays, pointers and operations pointers
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
c-arrays-pointers.ppt
c-arrays-pointers.pptc-arrays-pointers.ppt
c-arrays-pointers.ppt
 
c-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzzc-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzz
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
009 Data Handling .pptx
009 Data Handling .pptx009 Data Handling .pptx
009 Data Handling .pptx
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Python ppt
Python pptPython ppt
Python ppt
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

ESC112 Course lecture slides on pointers and memory allocation.pptx

  • 1. ESC101: Fundamentals of Computing Pointers and Memory Allocation Nisheeth
  • 2. ESC101: Fundamentals of Computing Pointers A pointer refers to an address in memory (2^64 – 1 possible addresses) Syntax for declaration: type *ptr; // ptr is pointer to a variable with data type “type” (examples: int *ptr, char *ptr) Can declare pointer and regular variables on same line Dereferencing a pointer gives the value stored at that address Dereferencing is done using * operator If ptr is a pointer to a variable i then *ptr means i For arrays, the name itself is the pointer and points to first element char a, b, *x, *y; x = &a, y = &b; int a, b, *x, *y; x = &a, y = &b; float a, b, *x, *y; x = &a, y = &b; The pointer itself takes 8 bytes in memory
  • 3. ESC101: Fundamentals of Computing Operator Name Symbol/Sign Associativity Brackets (array subscript), Post increment/decrement (), [] ++, -- Left Unary negation, Pre- increment/decrement, NOT, (de)reference, sizeof -, ++, --, !, *, &, sizeof Right Multiplication/division/ remainder *, /, % Left Addition/subtraction +, - Left Relational <, <=, >, >= Left Relational ==, != Left AND && Left OR || Left Ternary Conditional ? : Right Assignment, Compound assignment =, +=, -=, *=, /=, %= Right HIGH PRECEDENCE LOW PRECEDENCE Be careful, * can act as multiplication operator as well as dereference operator int a = 10; int *ptr = &a; printf("%d", 3**ptr); 30
  • 4. ESC101: Fundamentals of Computing Pointer Arithmetic Can take a pointer variable add and subtract integers Result depends on the type of the pointer Pointers to int advance by 4 upon adding 1 or doing ++ Pointers to int go back by 4 upon subtracting 1 or doing -- Pointers to char advance by 1 upon adding 1 or doing ++ Pointers to char go back by 1 upon subtracting 1 or doing -- Pointers to double advance by 8 upon adding 1 or doing ++ Pointers to double go back by 8 upon subtracting 1 or doing -- Note: Can’t increment/decrement an array pointer (more on this later)
  • 5. ESC101: Fundamentals of Computing Pointers and Arrays Array names are pointers to first element of the array Warning: consecutive addresses only assured in arrays a, b need not be placed side-by-side (i.e. 4 bytes apart) but arr[0], arr[1] will always be 4 bytes apart (int takes 4 bytes) Pointer arithmetic often used to traverse (go back and forth in) arrays and calculate offsets and both give value of the 3rd element in arr Warning: arr++ will give error, ptr++ will move pointer to arr[1] int arr[10] int a, b, *ptr = arr; arr[2] *(arr+2) The array name will always point to the first element of the array. Cannot change that! To do fancy pointer arithmetic, we should create a fresh pointer variable e.g. ptr
  • 6. ESC101: Fundamentals of Computing Pointers and Arrays a a[0] a[1] a[2] a[3] a[4] a[5] 22 55 000023 000023 000027 000031 000035 000039 000043 11 33 44 66 int a[6] = {11,22,33,44,55,66}; int *ptr = a; ptr 000023 ptr += 2; *ptr += 2; 35 printf("%d",ptr-a); 2 But the address difference is 31-23 = 8 Yes, but since this is int type, I treat 4 bytes as a unit Mr C also disallows subtraction of pointers of different types Yes, I will give an error if you, for e.g. subtract char* from int* 000031 If we really want to subtract a char* from int*, do a typecast!
  • 7. ESC101: Fundamentals of Computing Pointers and Strings Pointers are invaluable in managing strings Most library functions we use for strings (printf, scanf, strlen, strcat, strstr, strchr) operate with pointers Really do not care whether the pointer is to beginning of the string or in the middle of the string Start processing from the location given pointer “points”  char mind[] = "blown"; char str[] = "Hello World"; char *ptr = str; printf("%sn%s", str, ++ptr); Hello World ello World
  • 8. ESC101: Fundamentals of Computing Variable-length arrays So far we have always used arrays with constant length Waste of space – often allocate much more to be “safe” Also need to remember how much of array actually used Rest of the array may be filled with junk (not always zeros) In strings NULL character does this job For other types of arrays, need to do this ourselves  Lets us learn ways for on-demand memory allocation The secret behind getline and other modern functions Need to include stdlib.h for these functions malloc(), calloc(), realloc(), free() int c[10];
  • 9. ESC101: Fundamentals of Computing malloc – memory allocation We tell malloc how many bytes are required malloc allocates those many consecutive bytes Returns the address of (a pointer to) the first byte Warning: allocated bytes filled with garbage Warning: if insufficient memory, NULL pointer returned malloc has no idea if we are allocating an array of floats or chars – returns a void* pointer – typecast it yourself The allocated memory can be used safely as an array See example in accompanying code
  • 10. ESC101: Fundamentals of Computing calloc – contiguous allocation A helpful version of malloc that initializes memory to 0  However, slower than malloc since time spent initializing Use this if you actually want zero initialization Syntax a bit different – instead of total number of bytes, we need to send it two things length of array (number of elements in the array) number of bytes per element Sends back a NULL pointer if insufficient memory – careful! Need to typecast the pointer returned by calloc too! See example in accompanying code
  • 11. ESC101: Fundamentals of Computing realloc – revised allocation If you malloc-ed an array of 100 elements and suddenly find that you need an array of 200 elements  Can use realloc to revise that allocation to 200 elements Don’t use realloc to increase size of non-malloc arrays Use realloc only to increase size of calloc/malloc-ed arrays int *ptr = (int*)malloc(100 * sizeof(int)); I realize that. That is why I will copy those 100 elements to the new array of 200 elements  int *tmp = (int*)realloc(ptr, 200 * sizeof(int)); if(tmp != NULL) ptr = tmp; But what if I had precious data stored in those 100 elements You are the best Mr C int c[100]; int *ptr = (int*)realloc(c, 200 * sizeof(int)); // Runtime error I will also free the old 100 elements – you don’t have to write free() for them