C for Java Programmers & Lab 0porter/courses/comp530/f18/slides/C... · C for Java Programmers &...

Post on 27-Aug-2020

6 views 0 download

Transcript of C for Java Programmers & Lab 0porter/courses/comp530/f18/slides/C... · C for Java Programmers &...

COMP530:OperatingSystems

CforJavaProgrammers&Lab0

DonPorter

PortionscourtesyKevinJeffay

1

COMP530:OperatingSystems

SameBasicSyntax• DataTypes:int,char,[float]

– void- (untypedpointer)– Cancreateotherdatatypesusingtypedef

• NoStrings- onlychararrays– Lastcharacterneedstobea0

• Not‘0’,but‘\0’

COMP530:OperatingSystems

struct – C’sobject• typedef struct foo{

int a;void*b;void(*op)(int c);//functionpointer

}foo_t;//<------typedeclaration• Actualcontiguousmemory• Includesdataandfunctionpointers

COMP530:OperatingSystems

Pointers• Memoryplacementexplicit(heapvs.stack)

• Twosyntaxes(dot,arrow)intmain{

struct foof;struct foo*fp =&f;f.a =32;//dot:accessobjectdirectlyfp->a=33;//arrow:followapointerfp =malloc(sizeof(struct foo));fp->a=34;…

}

4

Stack Heapmain:f:a=0;b=NULL;op=NULL;

struct foo:a=0;b=NULL;op=NULL;

fp:PC

f:a=32;b=NULL;op=NULL;

f:a=33;b=NULL;op=NULL;

struct foo:a=34;b=NULL;op=NULL;

struct foo {int a;void*b;void(*op)(int c);

}

Ampersand:Addressoff

COMP530:OperatingSystems

Functionpointerexamplefp->op=operator;fp->op(32);//Sameascalling

//operator(32);

5

struct foo {int a;void*b;void(*op)(int c);

}

Codeinmemory:Main…

Operator:...

Stack Heapmain:f:a=0;b=NULL;op=NULL;

fp:

f:a=32;b=NULL;op=NULL;

f:a=33;b=NULL;op=NULL;

struct foo:a=34;b=NULL;op=NULL;

struct foo:a=34;b=NULL;op=

COMP530:OperatingSystems

MoreonFunctionPointers• Callowsfunctionpointerstobeusedasmembersofastruct orpassedasargumentstoafunction

• Continuingthepreviousexample:

voidmyOp(int c){/*…*/}/*…*/foo_t *myFoo =malloc(sizeof(foo_t));myFoo->op=myOp;//setpointer/*…*/myFoo->op(5);//Actuallycallsmyop

COMP530:OperatingSystems

NoConstructorsorDestructors• Mustmanuallyallocateandfreememory- NoGarbageCollection!– void*x=malloc(sizeof(foo_t));

• sizeof givesyouthenumberofbytesinafoo_t - DONOTCOUNTTHEMYOURSELF!

– free(x);• Memoryallocatorremembersthesizeofmalloc’edmemory

• Mustalsomanuallyinitializedata– Customfunction– memset(x,0,sizeof(*x))willzeroit

COMP530:OperatingSystems

MemoryReferences• ‘.’ - accessamemberofastruct

– myFoo.a =5;• ‘&’ - getapointertoavariable

– foo_t *fPointer =&myFoo;• ‘->’ - accessamemberofastruct,viaapointertothestruct– fPointer->a=6;

• ‘*’- dereferenceapointer– if(5==*intPointer){…}

• Withoutthe*,youwouldbecomparing5totheaddressoftheint,notitsvalue.

COMP530:OperatingSystems

Int exampleint x=5;//xisonthestackint *xp =&x;*xp =6;printf(“%d\n”,x);//prints6xp =(int *)0;*xp =7;//segmentationfault

9

Stackmain:

x:5

PC

xp:xp:NULL

x:6

COMP530:OperatingSystems

MemoryReferences,cont.• ‘[]’ - refertoamemberofanarray

char*str=malloc(5*sizeof(char));str[0]=‘a’;

– Note:*str=‘a’ isequivalent– str++;incrementsthepointersuchthat*str==str[1]

str

str[0] str[1] str[2] str[3] str[4]

str+1 str+2 str+3 str+4

COMP530:OperatingSystems

TheChickenorTheEgg?• ManyCfunctions(printf,malloc,etc)areimplementedinlibraries

• Theselibrariesusesystemcalls• Systemcallsprovidedbykernel• Thus,kernelhasto“reimplement” basicClibraries

– Insomecases,suchasmalloc,can’tusetheselanguagefeaturesuntilmemorymanagementisimplemented

COMP530:OperatingSystems

Formorehelp• manpagesareyourfriend!

– (notadatingservice)!– Ex:‘manmalloc’,or‘man3printf’

• Section3isusuallywherelibrarieslive- thereisacommand-lineutilityprintf aswell

• Use‘aproposterm’ tosearchformanentriesaboutterm

• TheCProgrammingLanguage byBrianKernighanandDennisRitchieisagreatreference.

COMP530:OperatingSystems

Lab0Overview• CprogrammingonLinuxrefresher

13

COMP530:OperatingSystems

• WriteasimpleCcharacterstreamprocessingprogramonLinux

• Readincharactersfrom“standardinput,”write80characterlinesto“standardoutput”replacing:– Everyenter/returncharacter(newline)byaspace– Everyadjacentpairofpercents “%%” withan“*”

◆ …isoutputas:» abcdefghijklmn*pqrstuvw*%yz ab

◆ Example(fora30characteroutputline):Thestring…» abcdefghijklmn%%pqrstuvw%%%yz

abc%%%def

???

Lab0- Overview

COMP530:OperatingSystems

◆ Thisistheonly outputyourprogramshouldgenerate» Thereshould benoprompts, debugging messages,statusmessages,...

%classroom> a.outAbcdefghijklmn%%pqrstuvw%%%yzabc%%%defAbcdefghijklmn*pqrstuvw*%yz ab1234567890123456789012345c*%def 12345678901234567890123

%classroom>

◆ Notethatyouroutputwillbeinterleavedwithyourinputontheconsole(indicatedinpurpleabove)» Thisisfine!» (Youcaneliminatethisifyouuse“I/Oredirection”)

COMP530:OperatingSystems

◆ Whenexecutingyourprogram,terminatestdin witha<enter/return><control-D>sequence» This(non-printable) charactersequenceisreferredtoas

“end-of-file”or“EOF”» IfyouuseI/Oredirectionandreadfromafileyouneednotaddthecontrol-D

characterattheend(Linuxdoesthisforyou)

control-D

%classroom> a.outAbcdefghijklmn%%pqrstuvw%%%yzabc%%%defAbcdefghijklmn*pqrstuvw*%yz ab1234567890123456789012345c*%def 12345678901234567890123

%classroom>

COMP530:OperatingSystems

• YoushouldallhaveLinuxaccountsintheDepartment– Ifyoudon’t,gotothelethelp@cs.unc.edu knowASAP!– Ifyouneedtohaveyourpasswordresetvisit

https://www.cs.unc.edu/webpass/onyen/• Logintoclassroom.cs.unc.edu todotheassignments• Createthedirectorystructurecomp530 inyourLinuxhomedirectory

• Executethemagicincantationstoprotectyourhomework:

fs sa ~/comp530 system:anyuser none

WorkingonHomeworkAssignments

Executetheseinstructionsbefore thenextsteps!

COMP530:OperatingSystems

Checkingoutthestartercode• Onceyouhaveagithub accountregistered

– Makesureyouaccepttheinvite:• Clickhttps://github.com/comp530-f18

• Clickthelinkinthehomeworktocreateaprivaterepo

• Then,onyourmachineorclassroom(substitutingyourteamfor‘team-don’– seethegreenclonebutton):git clonegit@github.com:comp530-f18/lab0-team-don.git

18

COMP530:OperatingSystems

• Commityourpendingchanges– Seetheoutputof:‘git status’– Committhechangesyouwishtosubmit:

• git addex2.c– Andanyotherfilesthatchanged

• git commit–m“Finishedlab0”• makehandin

– Youmayneedtoaddfilestoyour.gitignore file(andcommit)thatshouldnotbehandedin

– 2xcheckongithub:yourchangesarethere,andtagged‘handin’

Ifyoudon’tfollowtheseinstructionsexactly,yourHWwillnotbegraded!

Submittinghomework

COMP530:OperatingSystems

• Themachinesyoushoulduseforprogrammingare:– classroom.cs.unc.edu (primary)– snapper.cs.unc.edu (secondary)Accesseithermachineviaasecureshell(securetelnet)applicationonyourPC

• Youcandevelopyourcodeanywhereyoulikebut…

• Yourprogramswillbetestedonclassroom andcorrectnesswillbeassessedbasedontheirperformanceonclassroom– Alwaysmakesureyourprogramworksonclassroom!

Lab0ProgrammingNotes

COMP530:OperatingSystems

• Programs should be neatly formatted (i.e., easy to read) andwell documented

• In general, 75% of your grade for a program will be forcorrectness, 25% for programming style– For this assignment, correctness & style will each count for 50% of

your grade• Style refers to…

– Appropriate use of language features, including variable/procedure names, and

– Documentation (descriptions of functions, general comments, use of invariants, pre- and post conditions where appropriate)

– Simple test: Can I understand what you’ve done in 3 minutes?• Correctness will be assessed comprehensively!

– You’ve got to learn to test for “edge” and “corner cases”

Grading

COMP530:OperatingSystems

(“Hard But that is fine.Some of the grading scales for programming assignments were weird and not straightforward.Tended to place little emphasis on implementing what the assignment actually intended and emphasizedhow hard did you try to break your own program”)

• Programs that “mostly work” don’t cut it in a senior-level course!

Dr.Jeffay’s Experience

COMP530:OperatingSystems

• Working in teams on programming assignments is OK– But you can only collaborate with other students in the course– Every line of code handed in must be written exclusively by team

members themselves, and – All collaborators must be acknowledged in writing (and part of the

team)• Use of the Internet

– Using code from the Internet in any form is not allowed– Websites may be consulted for reference (e.g., to learn how a system

call works)– But all such websites used or relied on must be listed as a reference

in a header comment in your program– Warning: Sample code found on the Internet rarely helps the student

HonorCode:AcceptableandUnacceptableCollaboration