Lecture 1: Introduction To C - MIT OpenCourseWare

Transcription

6.S096 Lecture 1 – Introduction to CWelcome to the Memory JungleAndre KesslerAndre Kessler6.S096 Lecture 1 – Introduction to C1 / 30

Outline1Motivation2Class Logistics3Memory Model4Compiling5Wrap-upAndre Kessler6.S096 Lecture 1 – Introduction to C2 / 30

First Example (Python)def binary search( data, N, value ):lo, hi 0, N - 1while lo hi:mid ( lo hi ) / 2if data[mid] value:lo mid 1else:hi midif hi lo and data[lo] value:return loelse:return NAndre Kessler6.S096 Lecture 1 – Introduction to C3 / 30

First Example (C)size t binary search( int *data, size t N, int value ) {size t lo 0, hi N - 1;while( lo hi ) {size t mid lo ( hi - lo ) / 2;if( data[mid] value ) {lo mid 1;} else {hi mid;}}return ( hi lo && data[lo] value ) ? lo : N;}Andre Kessler6.S096 Lecture 1 – Introduction to C4 / 30

MotivationWhy C or C ?SpeedGraph of program speed across language implementations removed due to copyright restrictions.Source: -programs-are-fastest.php.Andre Kessler6.S096 Lecture 1 – Introduction to C5 / 30

MotivationWhy C or C ?PowerC: direct access to memory and memory management, expressive butterseC : all the power of C, plus stronger typing, object-oriented andgeneric programming, and moreAndre Kessler6.S096 Lecture 1 – Introduction to C6 / 30

MotivationWhy C or C ?UbiquityC: operating systems, drivers, embedded, high-performance computingC : large software projects everywhereExamples: Linux kernel, Python, PHP, Perl, C#, Google searchengine/Chrome/MapReduce/etc, Firefox, MySQL, MicrosoftWindows/Office, Adobe Photoshop/Acrobat/InDesign/etc, lots offinancial/trading software, Starcraft, WoW, EA games, Doom engine,and much, much moreAndre Kessler6.S096 Lecture 1 – Introduction to C7 / 30

MotivationEffective ProgrammingWriting good, standards-compliant code is not hard.Doing so will make your life much easier.There is a lot of bad code out there.You are better than that!Andre Kessler6.S096 Lecture 1 – Introduction to C8 / 30

MotivationEffective ProgrammingAnyone can write good, readable,standards-compliant code.Andre Kessler6.S096 Lecture 1 – Introduction to C9/ 30

Class LogisticsCourse SyllabusDay12345678910Andre KesslerTopicIntroduction to C: memory and the compilerSubtleties of C: memory, floating pointGuest lectures: Assembly and Secure CTransition from C to C Object-oriented programming in C Design patterns and anti-patternsGeneric programming: templates and moreProjects: putting it all togetherProjects: continuedGrab-bag: coding interviews, large projects6.S096 Lecture 1 – Introduction to C10 / 30

Class LogisticsGrading6 units U credit, graded Pass/FailCoding assignmentsThree assignments worth 20%, final worth 40%.Automatic instantaneous feedbackCode reviewsTwo reviews of code by your peersMore details laterTo Passat least 50% of available coding assignment pointsmust submit both code reviewsAndre Kessler6.S096 Lecture 1 – Introduction to C11 / 30

Class LogisticsTextbooksNone required.However, the following books are on reserve at the library and may beuseful as references. Highly recommended if you end up doing moreC/C coding after this course.RecommendedThe C Programming Language by B. Kernighan and D. Ritchie (“K&R”)The C Programming Language, 4th ed. by Bjarne StroustropEffective C , More Effective C , and Effective STL by Scott MeyersAndre Kessler6.S096 Lecture 1 – Introduction to C12 / 30

Class LogisticsThe Minimal C Programnothing.c: takes no arguments, does nothing, returns 0 (“exit success”)int main(void) {return 0;}1To compile: make nothing2Previous step produced an executable named nothing3To run: ./nothing4Surprise! Does nothing.But you probably have higher aspirations for your programs.Andre Kessler6.S096 Lecture 1 – Introduction to C13/ 30

Class LogisticsHello, world!hello.c: takes no arguments, prints “Hello, world!”, returns 0int main(void) {return 0;}Andre Kessler6.S096 Lecture 1 – Introduction to C14 / 30

Class LogisticsHello, world!hello.c: takes no arguments, prints “Hello, world!”, returns 0#include stdio.h int main(void) {return 0;}Andre Kessler6.S096 Lecture 1 – Introduction to C15 / 30

Class LogisticsHello, world!hello.c: takes no arguments, prints “Hello, world!”, returns 0#include stdio.h int main(void) {printf( "Hello, world!\n" );return 0;}Andre Kessler6.S096 Lecture 1 – Introduction to C16 / 30

Class LogisticsHello, world!hello.c: takes no arguments, prints “Hello, world!”, returns 0#include stdio.h int main(void) {printf( "Hello, world!\n" );return 0;}1To compile: make hello2Previous step produced an executable named hello3To run: ./hello4Hello, world!Andre Kessler6.S096 Lecture 1 – Introduction to C17 / 30

Memory ModelPointersHow do you get at this information about memory?Through pointers; that is, the & and * operatorsint a 5; The address of a is &a.int *a ptr &a; Read declarations from right to left.See it this way: “*a ptr is declared to be of type int.”You can apply & to any addressable value (“lvalue”)return &5;// error:lvalue required as unary ‘&’ operandAndre Kessler6.S096 Lecture 1 – Introduction to C18 / 30

Memory ModelIt’s all about the memoryint a 5;int *a ptr &a;&a&a ptrMemory tifieraa ptrNote: definitely a 64-bit machine, since the addresses are larger than232 .Andre Kessler6.S096 Lecture 1 – Introduction to C19 / 30

Memory ModelIt’s all about the memoryint a 5;int *a ptr &a;&a&a ptrMemory 00050x?Identifieraa ptrNote: definitely a 64-bit machine, since the addresses are larger than232 .Andre Kessler6.S096 Lecture 1 – Introduction to C20 / 30

Memory ModelIt’s all about the memoryint a 5;int *a ptr &a;&a&a ptrMemory 00050x7fff6f641914Identifieraa ptrNote: definitely a 64-bit machine, since the addresses are larger than232 .Andre Kessler6.S096 Lecture 1 – Introduction to C21 / 30

Memory ModelC Data TypesFor the bit counts, we’re assuming a 64-bit system.char (8)short (16), int (32),long (64), long long (64 )float (32), double (64), long double ( 80)Andre Kessler6.S096 Lecture 1 – Introduction to C22/ 30

Memory ModelC Data TypesTable of C data types removed due to copyright restrictions.Courtesy of re Kessler6.S096 Lecture 1 – Introduction to C23/ 30

CompilingDevelopment EnvironmentWe officially support development with gcc on Linux.If you don’t have a computer running Linux, then that’s what today’slab time is devoted to.Some options: SSH with PuTTY, Cygwin, Xcode on MacCreate a directory dev/Copy the file Makefile to this directory.To compile a file filename.c, just run “make filename”.Andre Kessler6.S096 Lecture 1 – Introduction to C24 / 30

CompilingWhat happens when we compile?#include stdio.h int do thing( float a, float b ) {/* do things */}void call(void) {/* do stuff */do thing( a, b );/* do more */}int main(void) {call();return 0;}Andre Kessler6.S096 Lecture 1 – Introduction to C25 / 30

CompilingWhat happens when we compile?Three functions main, call, and do thing.Object code is produced for eachWhen we run: the object code is loaded into memoryEach function that is called is in memory, somewhere.Andre Kessler6.S096 Lecture 1 – Introduction to C26 / 30

CompilingExamplesTime for some examples!Andre Kessler6.S096 Lecture 1 – Introduction to C27 / 30

CompilingWith great power comes great responsibilityC is focused on speed; always checking array bounds/memory accesswould slow you down.simple typo for( int i 0; i N; i ) can causecorruptionMemory corruption can cause totally unexpected, hard-to-debugbehavior at worstAt best: Segmentation fault (core dumped)(at least it’s more obvious!)Andre Kessler6.S096 Lecture 1 – Introduction to C28 / 30

Compiling“C makes it easy to shoot yourself in thefoot; C makes it harder, but when youdo, it blows your whole leg off.”— Bjarne Stroustrop, creator of the C programming languageAndre Kessler6.S096 Lecture 1 – Introduction to C29 / 30

Wrap-upWrap-up & FridayOpen labBring your laptops, get a C programming environment workingTest out the automatic graderClass on FridayWill cover floating point arithmetic, memory management, andheaders in more depth.Questions?Andre Kessler6.S096 Lecture 1 – Introduction to C30 / 30

MIT OpenCourseWarehttp://ocw.mit.edu6.S096 Effective Programming in C and C IAP 2014For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

“C makes it easy to shoot yourself in the foot; C makes it harder, but when you do, it blows your whole leg off.” — Bjarne Stroustrop, creator of the C programming language. Andre Kessler. 6.S