c programming 2 - university of the pacific · pointer arithmetic ì only addition and subtraction...
TRANSCRIPT
ìComputerSystemsandNetworksECPE170–JeffShafer–UniversityofthePacific
CProgramming2
LabSchedule
Activitiesì ThisWeek
ì IntrotoC2ì Lab4–CProgramming
Project
Deadlinesì Lab3–Feb4th2020
by5am
ì Lab4–Feb18th2020by5am
Spring2020ComputerSystemsandNetworks
2
PointerArithmetic
ì Onlyadditionandsubtractionareallowedwithpointers
ì Allpointersincreaseanddecreasebythelengthofthedata-typetheypointto
ì Exampleì Ifanintegerpointer,iptrholdsaddress32,then
aftertheexpressioniptr++,iptr willhold36(assumingintegeris4bytes).
ComputerSystemsandNetworks
3
Spring2020
Problem1Thenameofthearrayisactuallyapointerpointingtothefirstelementofthearray.
printf(“\n”, %u:”, array+3); //prints?______printf(“\n”, %u:”, *(array+3)); //prints?______
Subscript [0] [1] [2] [3] [4] Value 5 6 4 8 2
Address 65528 65532 65536 65540 65544
Consider an integer array named array.
printf(“\n %u:”, array); //prints 65528
printf(“\n %u:”, array+2); //prints 65536
printf(“\n %u:”, *(array+1)); //literally translates to array[1]. Prints 6
P1
ComputerSystemsandNetworks
4
Spring2020
PointersandFunctions:Callbyvaluevs.Callbyreference
Callbyvaluemain(){ a=5,b=6; update(a,b); printf(“%d”,a);}
update(int a, int b) { a=a-b;}
Thesearejustcopies.Nochangetooriginalvariables
Callbyreference(pointer)main(){ a=5,b=6; update(&a,&b); printf(“%d”,a);}
update(int *a,int *b) { *a=*a-*b;}
Modificationtoactualvariable
ComputerSystemsandNetworks
5
Spring2020
ìDynamicMemoryManagement
ComputerSystemsandNetworks
6
Spring2020
MemoryAllocationwithmalloc()
ì #include <stdlib.h>
ì void * malloc(int size) ì Allocateregioninmemory(aka“new”)ì Argument:Sizeofregioninbytestoallocateì Returnvalue:Pointertotheregion
ì void free(void * ptr) ì De-allocateregioninmemory(aka“delete”)ì Argument:Pointertotheregion
ComputerSystemsandNetworks
7
Spring2020
MemoryAllocationwithmalloc()
ì void * calloc(int count, int size) ì Basicallythesameasmalloc!
ì Imagineyouwantanarrayofelements…
ì Argument1:#ofelementstoallocateì Argument2:Sizeofeachelementinbytesì Returnvalue:Pointertotheregion
ComputerSystemsandNetworks
8
Spring2020
MemoryAllocationwithmalloc()
ì void * realloc(void *ptr, int size); ì Resizeadynamicregionofmemory
ì Notethatitmightmovetoanewaddress!
ì Argument:Pointertotheoriginalregionì Argument2:Desiredsizeinbytesofnewregionì Returnvalue:Pointertothenewregion
ì Itmightbeatthesameaddressifyoumadeitsmallerì Itmightbeatanewaddressifyoumadeitlarger
ComputerSystemsandNetworks
9
Spring2020
Malloc–1D
int *array; //array of integers
array = (int *)malloc(sizeof(int)*5);
60 64 68 72 76
array[0] array[1] array[2] array[3] array[4]
address:
value:
array(pointervariable)
value:????
pointeraddr:32
ComputerSystemsandNetworks
10
60
Spring2020
Malloc–2DAllocate4x5integers(Hintforlab4)
int **array; //a double pointer
array = (int **)malloc(sizeof(int *)*4);
for(i=0;i<4;i++) array[i] = (int *)malloc(sizeof(int)*5);
anarrayofintegerpointers
arrayofints
arrayofints
arrayofints
arrayofints
ComputerSystemsandNetworks
11
Spring2020
Malloc–3Dint ***array; //a triple pointer
anarrayofdoublepointers
amatrixofsinglepointers
a‘cuboid’ofintegers
ComputerSystemsandNetworks
12
Spring2020
Problem2
ì Dynamicallyallocatespacefora3-Dcolorimageofwidth,w;height,h;colorchannel,c.Anypixelisaccessedasimage[height][width][c].
P2
ComputerSystemsandNetworks
13
Spring2020
ìMemoryManagementInternals
Spring2019ComputerSystemsandNetworks
14
MemoryManagement
ì Whoimplementedmalloc()?
ì CStandardLibrary:#include <stdlib.h>
ì TherearedifferentCStandardLibraryimplementations!ì Android:Bionicì Apple:BSD-based/Proprietaryì Microsoft:ProprietaryCRuntimeLibraryì Linux:GNUCLibrary(glibc)
http://www.gnu.org/software/libc/
ComputerSystemsandNetworks
15
Spring2020
MemoryManagement
ì Wheredoesthemalloc()memorycomefrom?
ì TheHeap:ì Aregionofmemoryfordynamicmemoryallocationì Per-process–eachprogramgetsitsownheapì Managedbymalloc()andrelatedfunctionsì Differentfromthestack,whichisforstaticvariables
(knownatcompile-time)
ComputerSystemsandNetworks
16
Spring2020
MemoryManagement
ì malloc()outline:
1. Callmalloc()andrequestmemory
2. malloc()checksexistingheapsizeì Sufficient?Updatebookkeepingtomarkspaceas
“used”andreturnaddresstoyourprogramì Insufficient?
1. Calloperatingsystemviabrk()/nmap()togrowtheheap(plusalittleextraforfuturerequests)
2. Updatebookkeepingandreturnaddresstoyourprogram
ComputerSystemsandNetworks
17
Spring2020
MemoryManagement
ì Whydoweneedtocallfree()aftercallingmalloc()?ì Memoryleakì malloc()cannotre-usethatspaceever,because
itsinternalbookkeepingstillthinksthatregionisused
ì Willonlyberecovereduponterminatingprogramì Operatingsystemwipesoutallthememoryallocated
toyourprocess(stack,heap,etc…)
ComputerSystemsandNetworks
18
Spring2020
MemoryManagement
ì OScreatesvirtualmemoryspaceforprocesswhenstarted
ì Regionishuge(full32or64bitspace)ì Notfullymappedto
physicalmemoryì Otherwiseyoucould
onlyfit1programinmemory
ComputerSystemsandNetworks
19
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
VirtualMemorySpacefornewprocess
Spring2020
MemoryManagement
ì OSloadsintheprogramfromdisk
ì “Text”regionì Programcode
ì “Data”regionì Programfixed
data
ComputerSystemsandNetworks
20
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Spring2020
MemoryManagement
ì Stackcreatedtotrackprogramfunctioncallsandlocalvariables
ComputerSystemsandNetworks
21
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Spring2020
MemoryManagement
ì Heapcreatedtostoredynamicmemoryfrommalloc()andrelatedfunctions
ì Nottoscale–thisunusedregionishuge!
ComputerSystemsandNetworks
22
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Heap
(Unused/unmappedvirtualmemory)
Spring2020
MemoryManagement
ì Programstartsrunning
ì malloc() allocatessomememory
ComputerSystemsandNetworks
23
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Heap
(Unused/unmappedvirtualmemory)
Spring2020
MemoryManagement
ì Originalheapspaceeventuallyfillsup
ì malloc()requestsadditionalspacefromthekernelbyusingbrk()systemcall
ComputerSystemsandNetworks
24
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Heap
(Unused/unmappedvirtualmemory)
Newspace
Spring2020
MemoryManagement
ì free()deallocatesblocksfromtheheap
ComputerSystemsandNetworks
25
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Heap
(Unused/unmappedvirtualmemory)
Spring2020
MemoryManagement
ì Programterminates
ì OSexpungesentirevirtualaddressspaceì Everythingis
deleted
ComputerSystemsandNetworks
26
0x0000000000000000
0xFFFFFFFFFFFFFFFF (32or64bit)
Text(Programcode)
Data(Programdata)
Stack
Heap
(Unused/unmappedvirtualmemory)
Spring2020
BufferOverflowVulnerability
ì Whatisabufferoverflowbug?ì char buf1[8]="";
char buf2[8]=""; strcat(buf1, "excessive");
ì Endupoverwritingtwocharactersbeyondbuf1!
27
ComputerSystemsandNetworks Spring2020
BufferOverflowVulnerability
ì Whyisabufferoverflowbugdangerous?
ì Whatisbeyondmybufferinmemory?ì Othervariablesanddata?(probablybuf2)ì Thestack?(furtherout)ì Thereturnaddresstojumptoaftermyfunction
finishes?
ì Ifappisrunningasadministrator,attackernowhasfullaccess!
28
ComputerSystemsandNetworks Spring2020
MemoryManagement
ì LimitlessopportunitiesinCforerrorsregardingmemoryLì Forgettingtofree()somedynamicmemoryì Tryingtofree()dynamicmemorymorethanonceì Losingapointertodynamicmemory(memoryis“lost”)ì Accessingarrayelementspasttheendofthearrayì Mis-calculatingarraypointersthatmisstheirdesired
target
ì Willlearnatool(Valgrind)inLab5toanalyzeyourprogramanddetect/traceerrors
29
ComputerSystemsandNetworks Spring2020
What’stheError?
ComputerSystemsandNetworks
30
char *a = malloc(128*sizeof(char)); char *b = malloc(128*sizeof(char)); b = a; free(a); free(b);
http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Spring2020
What’sthe(Potential)Error?
ComputerSystemsandNetworks
31
char *a = malloc(128*sizeof(char)); dataLen = <some value...> // Copy “dataLen” bytes // starting at *data to *a memcpy(a, data, dataLen);
http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Spring2020
What’stheError?
ComputerSystemsandNetworks
32
ptr = (char *) malloc(strlen(string_A)); strcpy(ptr, string_A);
http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Spring2020
What’stheError?
ComputerSystemsandNetworks
33
int *get_ii() { int ii = 2; // Local stack variable return ⅈ } main() { int *ii; ii = get_ii(); ... Do stuff using ii pointer } http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Spring2020
ComputerSystemsandNetworks
34
http://xkcd.com/371/
Spring2020
MemoryManagement
ì What’saNULLpointer?ì Pointervalueis0x000000000ì Meaningisthatthepointerisnotpointing
anywhere
ì WhathappensifyoudereferenceaNULLpointer?ì Tellingthecomputertoreadfrom(orwrite)tothe
valuestoredinthepointer,whichis0x000000000ì Behaviorundefinedandgenerallyunpleasanton
variouscomputersystems
ComputerSystemsandNetworks
35
Spring2020
MemoryManagement
ì “Segfault”=SegmentationFault
ì Yourprogramtriedtoreadorwriteavirtualmemoryaddressthatisnotallowedì Triedtoreadmemoryoutsideofprogrambounds?ì Triedtowriteread-onlymemoryregions?(usedfor
programdata)
ì “Segmentation”wasthenameofanoldsystem(backbeforeIntel386processors)usedtodividephysicalcomputermemoryintomanyvirtualaddressregions,oneperapplicationprocessì TheSegfaultnamestuckeventhoughwenowusepaging
tomanagevirtualmemory
ComputerSystemsandNetworks
36
Spring2020
ìStructures
ComputerSystemsandNetworks
37
Spring2020
Structures
ComputerSystemsandNetworks
38
struct database { int id_number; int age; float salary; }; int main() { struct database employee; employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; }
Usefulwaytogrouprelatedvariables!
Spring2020
Problem3
ComputerSystemsandNetworks
39
P3
Declare a structure called board that contains: • a double character pointer matrix • two integer variables height and width denoting the
number of rows and columns in the matrix. Inside main, do the following: 1. Create a structure object called myboard,
initialize matrix to NULL, set height to 7 and width to 7 2. Dynamically allocate matrix to hold height x
width elements
Spring2020
Problem4
ComputerSystemsandNetworks
40
P4
ContinuewiththecodefromProblem3.Traversethe2Dmatrixofdimensionsheight(rows)andwidth(columns).WriteaCsnippettofindthefirstinstanceoflowercaseletter‘e’.Obtainallthelettersstartingfrom‘e’placeddiagonallydownwardsandtotherightinthismatrix.Storethelettersina1Darray,buffer.Makesurethatbufferisoflargeenoughsizetocontainalloftheletters.
Spring2020
Problem5
ComputerSystemsandNetworks
41
P5
ContinuewiththecodefromProblem3.free()isactuallyareverseoperationofmalloc.Thestepsyouuseforfreeareoppositeofthestepsformalloc.Freethedynamicallyallocated2DmatrixyoucreatedinProblem3.
Spring2020
ComputerSystemsandNetworks
42
You’rereadyto
BeginLab4!
Spring2020