SlideShare a Scribd company logo
1 of 13
ESC101: Fundamentals of Computing
Pointers and Memory Allocation
(Continued)
Nisheeth
ESC101: Fundamentals of
Computing
So far about pointers..
What is a pointer - An address in memory
How to declare a pointer variable - type * ptrName;
Every pointer variable has a data type
type * (not type) is data type of above pointer ptrName
After declaration, can use *ptrName to dereference
Pointer arithmetic. Can add/subtract to go forward/back
Pointers and arrays (array name is pointer to first element)
Pointers and strings (string name is pointer to first char)
Memory allocation functions (malloc, calloc, realloc)
ESC101: Fundamentals of
Computing
Reminder: Some basics about arrays and pointers
Consider an array int arr[6] = {2,4,1,3,5,7};
arr (name of the array) is the same as &arr[0]
Address of the i-th element is arr+i or &arr[i]
Value of the i-th element is *(arr+i) or arr[i]
All of the above is true for any type of array
String’s name is the pointer to the first character of string (so
string pointer is of type char *)
String’s name is used directly by scanf to read the full string
String’s name is used directly by printf to print the full string
Without &
ESC101: Fundamentals of
Computing
Pointers and strings: A simple example
char str[] =“Array name is a pointer”;
char *ptr = str + 6; /*initialize*/
printf(“%s”,ptr);
ptr points to str[6]. printf prints
the string starting from str[6].
name is a pointer
str[0] str[5] str[10]
‘ ’
‘a’
str[15]
‘A’ ‘r’ ‘r’ ‘a’ ‘y’ ‘a’
‘n’
str
ptr
‘i’ ‘s’
‘e’ ‘ ’ ‘ ’
‘m’
‘n’ ‘t’ ‘e’ ‘r’ ‘0’
str[23]
str[16]
Output
‘p’ ‘o’ ‘i’
ESC101: Fundamentals of
Computing
Back to memory allocation related functions
malloc calloc
realloc
free
ESC101: Fundamentals of
Computing
malloc: Example
float *f;
f= (float *) malloc(10 * sizeof(float));
A pointer to float (or several floats)
Size big enough to hold 10 floats.
Note the use of sizeof to keep it
machine independent
malloc evaluates its arguments at
runtime to allocate (reserve) space.
Returns a void * pointer to first
address of allocated space.
Explicit type
casting to convey
user’s intent
ESC101: Fundamentals of
Computing
malloc: Example
float *f; int n;
scanf(“%d”, &n);
f= (float *) malloc(n * sizeof(float));
f[0] = 0.52;
scanf(“%f”, &f[3]); //Overflow if n<=3
printf(“%f”, *f + f[0]);
Key Point: The size argument can be a variable
or non-constant expression!
After memory
is allocated,
pointer
variable
behaves as if
it is an array!
This is because, in C, f[i] simply means *(f+i).
ESC101: Fundamentals of
Computing
calloc
Similar to malloc except for zero initialization
Syntax is slightly different from malloc
float *f;
f= (float *) calloc(10, sizeof(float));
How many
elements?
Size of each
element
ESC101: Fundamentals of
Computing
Memory leaks
Situation where memory allocated earlier
becomes unusable and blocked 
000000
000001
000002
000003
000004
000005
000006
000007
000008
000009
000010
000011
000012
000013
000014
000015
000016
000017
000018
000019
000020
000021
000022
000023
…
* * * * * * * *
int *ptr; // may contain a junk address now
ptr = (int*)malloc(3 * sizeof(int));
…
ptr = (int*)malloc(2 * sizeof(int));
ptr
ptr[0]
ptr[1]
ptr[2]
0 0 0 0 0 1 0 1
0 0 0 1 0 0 0 1
ptr will take 8 bytes to store –
sorry for not drawing accurately
ptr[0]
ptr[1]
If you keep losing memory like this,
soon your program may crash!
ESC101: Fundamentals of
Computing
free
Used to deallocate (free) memory allocated
using malloc/calloc/realloc
Don’t use freed memory or free memory twice
or free non-malloc/calloc/realloc-ed arrays –
will cause segfault or runtime error!
000000
000001
000002
000003
000004
000005
000006
000007
000008
000009
000010
000011
000012
000013
000014
000015
000016
000017
000018
000019
000020
000021
000022
000023
…
* * * * * * * *
int *ptr; // may contain a junk address now
char str[3];
ptr = (int*)malloc(3 * sizeof(int));
free(ptr);
printf("%d", ptr[1]);
ptr
ptr[0]
ptr[1]
ptr[2]
0 0 0 0 0 1 1 0
str[0]
str[1]
str[2]
0 0 0 0 1 0 0 1
free(str); // runtime error
str
I always free all memory when a program
ends. You only have to worry about freeing
memory that you asked to be allocated
ESC101: Fundamentals of
Computing
Library analogy for malloc/free
malloc/calloc is like borrowing a book from library
If that book unavailable, cannot use it (NULL pointer)
1000+ students in Y20 but only 50 copies of Thomas' Calculus
free is like returning a book so others can use it after you
If you keep issuing books without returning, eventually library
will stop issuing books to you and impose a fine
Cannot use a book after returning it (cannot use an array
variable after it has been freed)
Cannot return a book you do not have (cannot free memory that
has been already freed)
Of course, if you re-issue a book you can return it again
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 resize of non-malloc arrays
Use realloc only to resize 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 I had so much
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
If insufficient memory, I will
not free old memory but
just return NULL pointer
A bit system-dependent. If
insufficient memory, Prutor
programs will simply crash
ESC101: Fundamentals of
Computing
getline (reading string of any length)
Read a single line of text from input (i.e. till 'n')
Uses realloc-like methods to expand array size
Needs a malloc-ed array for this reason
If user input doesn’t fit inside original array, str will contain
pointer to expanded array, len will be length of new array
int len = 11; // I only expect 10 characters to be entered
char *str = (char*)malloc(len * sizeof(char));
getline(&str, &len, stdin);
char **ptrstr = &str;
getline(ptrstr, &len, stdin); // Alternate way to use getline
Pointer to a pointer simply stores
the address of a pointer variable
printf("%ld",*ptrstr) will print address of first char in str
printf("%c",**ptrstr) will print the first char in str
printf("%s",*ptrstr) will print entire string str
WARNING: len may be larger than length of input + 1
Get actual length of input using strlen() from string.h
Inception?


More Related Content

Similar to Pointers and Memory Allocation ESC101.pptx

Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structureSaad Gabr
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.Mohamed Fawzy
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxVeerannaKotagi1
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMohammad Usman
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocationGrishma Rajput
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationNaveen Gupta
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGem WeBlog
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
Chapter09-10 Pointers and operations .PPT
Chapter09-10  Pointers and operations .PPTChapter09-10  Pointers and operations .PPT
Chapter09-10 Pointers and operations .PPTShalabhMishra10
 
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
 

Similar to Pointers and Memory Allocation ESC101.pptx (20)

Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
See through C
See through CSee through C
See through C
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Chapter09-10.PPT
Chapter09-10.PPTChapter09-10.PPT
Chapter09-10.PPT
 
Chapter09-10 Pointers and operations .PPT
Chapter09-10  Pointers and operations .PPTChapter09-10  Pointers and operations .PPT
Chapter09-10 Pointers and operations .PPT
 
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
 

Recently uploaded

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
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...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

Pointers and Memory Allocation ESC101.pptx

  • 1. ESC101: Fundamentals of Computing Pointers and Memory Allocation (Continued) Nisheeth
  • 2. ESC101: Fundamentals of Computing So far about pointers.. What is a pointer - An address in memory How to declare a pointer variable - type * ptrName; Every pointer variable has a data type type * (not type) is data type of above pointer ptrName After declaration, can use *ptrName to dereference Pointer arithmetic. Can add/subtract to go forward/back Pointers and arrays (array name is pointer to first element) Pointers and strings (string name is pointer to first char) Memory allocation functions (malloc, calloc, realloc)
  • 3. ESC101: Fundamentals of Computing Reminder: Some basics about arrays and pointers Consider an array int arr[6] = {2,4,1,3,5,7}; arr (name of the array) is the same as &arr[0] Address of the i-th element is arr+i or &arr[i] Value of the i-th element is *(arr+i) or arr[i] All of the above is true for any type of array String’s name is the pointer to the first character of string (so string pointer is of type char *) String’s name is used directly by scanf to read the full string String’s name is used directly by printf to print the full string Without &
  • 4. ESC101: Fundamentals of Computing Pointers and strings: A simple example char str[] =“Array name is a pointer”; char *ptr = str + 6; /*initialize*/ printf(“%s”,ptr); ptr points to str[6]. printf prints the string starting from str[6]. name is a pointer str[0] str[5] str[10] ‘ ’ ‘a’ str[15] ‘A’ ‘r’ ‘r’ ‘a’ ‘y’ ‘a’ ‘n’ str ptr ‘i’ ‘s’ ‘e’ ‘ ’ ‘ ’ ‘m’ ‘n’ ‘t’ ‘e’ ‘r’ ‘0’ str[23] str[16] Output ‘p’ ‘o’ ‘i’
  • 5. ESC101: Fundamentals of Computing Back to memory allocation related functions malloc calloc realloc free
  • 6. ESC101: Fundamentals of Computing malloc: Example float *f; f= (float *) malloc(10 * sizeof(float)); A pointer to float (or several floats) Size big enough to hold 10 floats. Note the use of sizeof to keep it machine independent malloc evaluates its arguments at runtime to allocate (reserve) space. Returns a void * pointer to first address of allocated space. Explicit type casting to convey user’s intent
  • 7. ESC101: Fundamentals of Computing malloc: Example float *f; int n; scanf(“%d”, &n); f= (float *) malloc(n * sizeof(float)); f[0] = 0.52; scanf(“%f”, &f[3]); //Overflow if n<=3 printf(“%f”, *f + f[0]); Key Point: The size argument can be a variable or non-constant expression! After memory is allocated, pointer variable behaves as if it is an array! This is because, in C, f[i] simply means *(f+i).
  • 8. ESC101: Fundamentals of Computing calloc Similar to malloc except for zero initialization Syntax is slightly different from malloc float *f; f= (float *) calloc(10, sizeof(float)); How many elements? Size of each element
  • 9. ESC101: Fundamentals of Computing Memory leaks Situation where memory allocated earlier becomes unusable and blocked  000000 000001 000002 000003 000004 000005 000006 000007 000008 000009 000010 000011 000012 000013 000014 000015 000016 000017 000018 000019 000020 000021 000022 000023 … * * * * * * * * int *ptr; // may contain a junk address now ptr = (int*)malloc(3 * sizeof(int)); … ptr = (int*)malloc(2 * sizeof(int)); ptr ptr[0] ptr[1] ptr[2] 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 ptr will take 8 bytes to store – sorry for not drawing accurately ptr[0] ptr[1] If you keep losing memory like this, soon your program may crash!
  • 10. ESC101: Fundamentals of Computing free Used to deallocate (free) memory allocated using malloc/calloc/realloc Don’t use freed memory or free memory twice or free non-malloc/calloc/realloc-ed arrays – will cause segfault or runtime error! 000000 000001 000002 000003 000004 000005 000006 000007 000008 000009 000010 000011 000012 000013 000014 000015 000016 000017 000018 000019 000020 000021 000022 000023 … * * * * * * * * int *ptr; // may contain a junk address now char str[3]; ptr = (int*)malloc(3 * sizeof(int)); free(ptr); printf("%d", ptr[1]); ptr ptr[0] ptr[1] ptr[2] 0 0 0 0 0 1 1 0 str[0] str[1] str[2] 0 0 0 0 1 0 0 1 free(str); // runtime error str I always free all memory when a program ends. You only have to worry about freeing memory that you asked to be allocated
  • 11. ESC101: Fundamentals of Computing Library analogy for malloc/free malloc/calloc is like borrowing a book from library If that book unavailable, cannot use it (NULL pointer) 1000+ students in Y20 but only 50 copies of Thomas' Calculus free is like returning a book so others can use it after you If you keep issuing books without returning, eventually library will stop issuing books to you and impose a fine Cannot use a book after returning it (cannot use an array variable after it has been freed) Cannot return a book you do not have (cannot free memory that has been already freed) Of course, if you re-issue a book you can return it again
  • 12. 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 resize of non-malloc arrays Use realloc only to resize 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 I had so much 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 If insufficient memory, I will not free old memory but just return NULL pointer A bit system-dependent. If insufficient memory, Prutor programs will simply crash
  • 13. ESC101: Fundamentals of Computing getline (reading string of any length) Read a single line of text from input (i.e. till 'n') Uses realloc-like methods to expand array size Needs a malloc-ed array for this reason If user input doesn’t fit inside original array, str will contain pointer to expanded array, len will be length of new array int len = 11; // I only expect 10 characters to be entered char *str = (char*)malloc(len * sizeof(char)); getline(&str, &len, stdin); char **ptrstr = &str; getline(ptrstr, &len, stdin); // Alternate way to use getline Pointer to a pointer simply stores the address of a pointer variable printf("%ld",*ptrstr) will print address of first char in str printf("%c",**ptrstr) will print the first char in str printf("%s",*ptrstr) will print entire string str WARNING: len may be larger than length of input + 1 Get actual length of input using strlen() from string.h Inception? 