lecture 6: memory, part 4ix.cs.uoregon.edu/~hank/212/lectures/cis212_f19_lec6.pdf · pause and do...
TRANSCRIPT
Hank Childs, University of OregonOctober 17, 2019
Lecture 6:Memory, part 4
__. __ .__ __. __ ___ ___ ______ ___ .__ __. _______ _______ ___ .___________. ___| | | | | \ | | | | \ \ / / / | / \ | \ | | | \ | \ / \ | | / \| | | | | \| | | | \ V / | ,----' / ^ \ | \| | | .--. | | .--. | / ^ \ `---| |----` / ^ \| | | | | . ` | | | > < | | / /_\ \ | . ` | | | | | | | | | / /_\ \ | | / /_\ \| `--' | | |\ | | | / . \ __ | `----.__ / _____ \ | |\ | | '--' | | '--' | / _____ \ | | / _____ \\______/ |__| \__| |__| /__/ \__\ (_ ) \______(_ ) /__/ \__\ |__| \__| |_______/ |_______/ /__/ \__\ |__| /__/ \__\
_______.___________..______ __ __ ______ .___________. __ __ .______ _______ _______. / | || _ \ | | | | / || || | | | | _ \ | ____| / | | (----`---| |----`| |_) | | | | | | ,----'`---| |----`| | | | | |_) | | |__ | (----` \ \ | | | / | | | | | | | | | | | | | / | __| \ \
.----) | | | | |\ \----.| `--' | | `----. | | | `--' | | |\ \----.| |____.----) ||_______/ |__| | _| `._____| \______/ \______| |__| \______/ | _| `._____||_______|_______/
C&Memory• Callowsyoutodirectlyaccessmemory• Thereisno“babysitter”thatmonitorsyourmemoryaccesses– Unlessyouwanderoutsidea“segment,”inwhichcaseyourprogramcrashes
• Thishelpsperformance• Butmakesprogrammingdifficult– noseatbelts• HOWEVER:thereareprogramsthatwillmonitoryourmemoryaccessesandletyouknowwhenyouhavedonebadthings– valgrind &gdb
Thisweek’slab…
• Ifyou“domemorywrong,”thenyourprogramwillcrash
• Howtofix?• Specialprogram:gdb (GNUdebugger)– gdb cangiveyoulotsofhintsaboutwhyyourprogramcrashed!
NOCLASSTUESDAY
• InsteadYouTubelecture• Postedthisweekend• WillbeentirelyabouthowtodoProject2D
• (2Cdiscussedlaterthislecture)
Whatshouldyoubedoing?
• Duetoday:2B• 2Cmaybepostedtonightifwemakeitfarenoughinlecture
• Readingthetextbook,ifyouhavenotdoneitalready– Chapter2.1,2.2,2.3,2.4.,2.5,and2.6.1– Chapter4.1(butnot4.1.2),4.2-4.4–à willbeanupcomingquizondetailsinthebook(thingsIhavenotlecturedonwillbefairgame)
Review
Pointers• Pointer:pointstomemorylocation– Denotedwith‘*’– Example:“int *p”
• pointertoaninteger– Youneedpointerstogettoheapmemory
• Addressof:getstheaddressofmemory– Operator:‘&’– Example:
int x;int *y=&x;ß thisexampleispointingtoanautomaticvariable,notadynamicvariable
Whatisanarray?
• Blockofcontiguousmemory• IfelementseachhavesizeNbytesandthereareMelements,themN*Mcontiguousbytes
• LetAbeaddressofthebeginningofthearray• ThenA[0]isat“A”• AndA[1]isat“A+N”• A[2]isat“A+2*N”• andsoon…
Dynamicmemoryworksdifferently
• Youallocateit,itstaysarounduntilyoude-allocateitortheprogramends
• Important:youneedawaytokeeptrackofmemory– Ifnot,thememorywillbe“leaked.”
• Soweneedawayofmanagingdynamicmemory.
• TheconceptfordoingthisinCisPOINTERS
DynamicMemoryAllocation
• Specialbuilt-infunctiontoallocatememoryfromheap:malloc– InteractswithOperatingSystem– Argumentformalloc ishowmanybytesyouwant
• Alsobuilt-infunctiontodeallocate memory:free
free/malloc exampleEnablescompilertoseefunctionsthataren’tinthisfile.Moreonthisnextweek.
sizeof isabuiltinfunctioninC.Itreturnsthenumberofbytesforatype(4bytesforint).
don’thavetosayhowmanybytestofree…theOSknows
AutomaticvsDynamic
• Automaticmemorylivesonlyforitscurrentscope
• Dynamicmemorylivesuntilyoufreeit,oruntiltheprogramends
Thisisjustfine…
Thisisnotfine…
Andhereitgoeswrong…
Pauseanddoanexampleandfilmit
MemorySegments• Yourprogramisdividedinto4segments:– Codesegment:wherethemachinecodeinstructionsare
– Datasegment:wheretheglobalvariableslive…andotherthings
– “Stack”:whereautomaticmemorylives– “Heap”:wheredynamicmemorylives– Note:stack&heaparedatastructuresandwewilllearnmoreaboutthemlater.
Ifyouaccessmemoryaddressesoutsideyoursegments,yougeta“segmentationfault”…whichcausesacrash
“StackOverflow”
Stack Heap
Andinsomecasesitdoesn’thavetohittheheap.Justtakemorememorythanintended.
CharacterStrings
ASCIICharacterSet
imagesource:granneman.com
TherehavebeenvariousextensionstoASCII…nowmorethan128characters
Manyspecialcharactersarehandledoutsidethisconvention
SomeSpecialCharacters
New:%cprintscharacter
characterstrings
• Acharacter“string”is:– anarrayoftype“char”– thatisterminatedbytheNULLcharacter
• TheClibraryhasmultiplefunctionsforhandlingstrings
buildingacharacterstring
New:%sprints“strings”(arraysofcharsterminatedby\0)
buildingacharacterstring
Compilerautomaticallyaddsa\0foryou!
Didyounotice
• CharactersinCaresinglequotes:‘A’• StringsinCaredoublequotes:“helloworld”• Astringofasinglecharacterisstilldoublequotes:“A”– (Andthisisactually“A\0”)
Characterstringsexample
UsefulClibrarystringfunctions• strcpy:stringcopy• strncpy:stringcopy,butjustfirstNcharacters• strlen:lengthofastring
UsefulClibrarystringfunctions• strcpy:stringcopy• strncpy:stringcopy,butjustfirstNcharacters• strlen:lengthofastring
Whathappenedhere?
MoreusefulClibrarystringfunctions
source:cplusplus.com
argc &argv
• twoargumentstoeveryCprogram• argc:howmanycommandlinearguments• argv:anarraycontainingeachofthearguments
• “./a.out hankchilds”• à argc ==3• à argv[0]=“a.out”,argv[1]=“hank”,argv[2]=“childs”
Project2C• Assignedtoday• DueFridayOct25• Parsingfloatingpointnumbers(e.g.,-3.68)
• Lotsofhintsinprompt
Enums,structs,typedef,union
Enums
• Enums makeyourowntype– Typeis“listofkeywords”
• Enums areusefulforcodeclarity– Alwayspossibletodothesamethingwithintegers
• Becarefulwithenums– …youcan“contaminate”abunchofusefulwords
enum example
Ckeyword“enum”–
meansenumdefinitionis
coming
Thisenumcontains6differentstudenttypes
semi-colon!!!
enum example
enums translatetointegers…andyoucansettheirrange
Butenums canbeeasiertomaintainthanintegers
Ifyouhadusedintegers,thenthisisabiggerchangeandlikelytoleadtobugs.
SimpleDataTypes
• float• double• int• char• unsignedchar
Allofthesearesimpledatatypes
Structs:acomplexdatatype
• Structs:mechanismprovidedbyCprogramminglanguagetodefineagroupofvariables– Variablesmustbegroupedtogetherincontiguousmemory
• Alsomakesaccessingvariableseasier…theyareallpartofthesamegrouping(thestruct)
struct syntaxCkeyword“struct”–
meansstructdefinitionis
coming
Thisstructcontains6doubles,meaningitis48bytes
semi-colon!!!
“.”accessesdatamembersforastruct
Declaringaninstance
Nestedstructs
accessesdirpartofRay
accessesdirectionZpartofDirection(partofRay)
typedef
• typedef:tellcompileryouwanttodefineanewtype
savesyoufromhavingtotype“struct”everytimeyoudeclareastruct.
Otherusesfortypedef
• Declareanewtypeforcodeclarity– typedef int MilesPerHour;• MakesanewtypecalledMilesPerHour.• MilesPerHour worksexactlylikeanint.
• Alsousedforenums &unions– sametrickasforstructs …typedef savesyouaword
Soimportant:struct datamemberaccessisdifferentwithpointers
Pointers:use“->”Instances(i.e.,notpointers):use“.”
Unions
• Union:specialdatatype– storemanydifferentmemorytypesinonememorylocation
Whendealingwiththisunion,youcantreatitasafloat,asanint,oras
4characters.
Thisdatastructurehas4bytes
Unions
Whyareunionsuseful?
UnionsExample
UnionsExample
BonusSlides
Importantnoteondebugging:bufferingandprintf
• Important:printf isbuffered• So:– printf putsstringinbuffer– otherthingshappen– bufferiseventuallyprinted
• Butwhataboutacrash?– printf putsstringinbuffer– otherthingshappen…includingacrash– bufferisneverprinted!
Onesolution:fflush(stdout)
Let’spauseanddoavideoonfflush
mv:Unixcommandforrenamingafile