CSE 451 C refresher.

Slides:



Advertisements
Similar presentations
Copyright 2013 – Noah Mendelsohn Compiling C Programs Noah Mendelsohn Tufts University Web:
Advertisements

Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT.
CSE 303 Lecture 16 Multi-file (larger) programs
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
CSE 451: Operating Systems Section 1. Why are you here? 9/30/102.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
C and Data Structures Baojian Hua
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 451: Operating Systems Section 1 Intro, C programming, project 0.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
C++ Memory Overview 4 major memory segments Key differences from Java
CSE 451: Operating Systems Section 1. Why are you here?  Because you want to work for Microsoft and hack on the Windows kernel? 3/29/  Because.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 8 – C: Miscellanea Control, Declarations, Preprocessor, printf/scanf.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
C++ Functions A bit of review (things we’ve covered so far)
CSE 451 Section 1 C Refresher (or introduction?) Project 0.
Variables Bryce Boe 2012/09/05 CS32, Summer 2012 B.
1 Binghamton University Exam 1 Review CS Binghamton University Birds eye view -- Topics Information Representation Bit-level manipulations Integer.
Homework Notes from Sean
Lecture 3 Translation.
Memory-Related Perils and Pitfalls in C
Content Coverity Static Analysis Use cases of Coverity Examples
CS/COE 0449 (term 2174) Jarrett Billingsley
Computer Organization and Design Pointers, Arrays and Strings in C
Overview 4 major memory segments Key differences from Java stack
C Primer.
CSE 374 Programming Concepts & Tools
A bit of C programming Lecture 3 Uli Raich.
Motivation and Overview
C Programming Tutorial – Part I
Functions Separate Compilation
Checking Memory Management
C Basics.
Overview 4 major memory segments Key differences from Java stack
Memory Management III: Perils and pitfalls Mar 13, 2001
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Programming in C Miscellaneous Topics.
CSE451 Fall 2008 Section 1 Roxana Geambasu
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Programming in C Miscellaneous Topics.
Introduction to Static Analyzer
Homework Finish up K&R Chapters 3 & 4
Compiler vs linker The compiler translates one .c file into a .o file
The Three Attributes of an Identifier
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
SPL – PS1 Introduction to C++.
SPL – PS2 C++ Memory Handling.
Week 9 - Monday CS222.
Introduction to C CS 3410.
Presentation transcript:

CSE 451 C refresher

Motivation: Why C? Why couldn't we write an entire OS in, say, Java? Java is interpreted -- the .class files need to be run using the Java VM. What would the Java VM itself run on? This needs to be native code. OS needs precise control -- programmer needs to be able to reason precisely about the code execution. Things like garbage collection are unpredictable -- they can happen at any time. This is unacceptable inside the OS. Some tasks may run in modes which necessarily must be completed very quickly, such as when interrupts are disabled (you'll learn about this more, later). Memory management inside the OS is much more constrained; you typically have multiple "pools" of memory from which to allocate objects -- a single simple "new" operator no longer cuts it. C was invented at Bell Labs specifically for OS Programming (UNIX) in 1977. Its design goals were to be more portable and readable than assembly, but to compile very simply to assembly in a straightforward manner. (We're still working on the portability bit, even in 2006!) Any other reasons? Can you think of drawbacks to using C? Ask: --------- Before: Who here knows and has experience in Java? C++? C? (assembly?) After: Why not C++? Still too much overhead; inherited classes and things like virtual dispatch make debugging hard.

Differences in Compilation Java: .java files  .class files, which are run through a VM. Can be "zipped" together in a .jar, but still functionally a set of separate files.  C: .c files  .o files; header files used to share definitions. .o files are linked together into libraries and/or executables. Use GCC to compile and link c code…

Differences in Libraries In Java, you had the Class Libraries (java.util, java.String, java.Math, etc..). You would import a namespace such as java.util.* into the active file. This let the VM know that names in this file referred to names from that namespace.  In C, you have a set of standard functions rolled together in "libc." There is no concept of namespaces. To use a function that isn't a part of the current file, you need to predefine it as extern. These definitions or prototypes are in a set of header files which you can include. The linker will then match up all the library functions used with your uses of them in the final compilation step.  To include one file inside another, we use a preprocessor directive, of the form: #include<filename.h> There is no preprocessor in Java. In C, the preprocessor reads the files, looking for lines beginning with '#‘ called preprocessor directives, and then performs an appropriate action, effectively rewriting the file before it is consumed by the compiler. Mention at the end: ------------------------ Discuss header files Header files by convention end with .h (although they don’t have to) They usually define “public – although there is no such concept in C” functionality (kind of like an interface in Java) but do not implement it An #include directive causes the contents of the included-file to be inserted verbatim "on top" of the include directive. This can cause recursively nested file inclusion. The compiler will warn you if there's a loop.

Differences w.r.t. OOP There are no classes in C! All methods are "static" in the Java sense -- but don't declare them with the static keyword, unless you know exactly what you're doing; it means something else in C. data structures are stored in structs -- which are like classes with all members public, and no functions. You must manipulate these with methods "outside" of the structure. In Java, all objects are stored in the heap. In C, structs may live in the heap, on the stack, or in global space. If you allocate a struct in the heap, you will receive a pointer to the struct. Effectively, this is the same as a reference in Java -- it contains the address of the struct, in memory. Static keyword in C: two distinct meanings: “static local variables” are scoped variables but have a static lifespan (eg a static variable in a function would be scoped to the function but preserve its value across function calls.) “static global variables”

Things to get used to about C Pointers and pointer arithmetic Static vs. dynamic memory allocation Call-by-value vs. call-by-reference Structures, typedef Mention function pointers

Pointers Example Use: Pointer arithmetic: int a = 5; int b = 6; int *pa = &a; // Declares a pointer to a with value as the // address of a. *pa = b; // Changes the value of a to b, that is a == 6 pa = &b; // Changes pa to point to the place where b is on // the stack. Pointer arithmetic: int foo[2]; // foo is a pointer to the beginning of the array *(foo + 1) = 5; // the second int in the array is set to 5 Note with pointers: ---------------------- * operator is used to declare a pointer an dereference one & operator is used to take an address of a variable Note with pointer arithmetic: -------------------------------- The compiler knows what the type of the pointer is (unless it is a void*) and will allow you to manipulate pointers with correct alignment. Function Pointers int (*pt2Function)(float, char, char) = NULL; // C

Struct and Typedef struct foo_s { // defines a type that is referred int x; // to as a “struct foo_s” int y; }; // don’t forget this ; struct foo_s foo; // declares a foo struct on the stack of // type struct foo_s foo.x = 1; // access the x field typedef struct foo_s *foo_t; // use typedef to create an alias // allowing you to now use foo_t // to declare variables instead. foo_t another_foo = (foo_t)malloc(sizeof(struct foo_s)); another_foo->x = 2; // another_foo is a pointer to a struct foo_s // on the heap. The “->” operator dereferences // the pointer and accesses the field x.

Pass-By-Value, Pass-By-Reference int doSomething(int x) { return x+1; // x is copied into the stack frame of // this function, and the local copy is // modified and returned } void doSomethingElse(int *x) { *x += 1; // The pointer is copied into the stack // frame, then dereferenced and the // memory being pointed to is changed void foo() { int x = 5; int y = doSomething(x); // y will get 6, but x will be unchanged doSomethingElse(&x); // changes the value of x to 6 Mention C++

Common C Pitfalls (1) What’s wrong and how to fix it? char* get_city_name(double latitude, double longitude) { char city_name[100]; … return city_name; }

Common C Pitfalls (1) Problem: return pointer to statically allocated memory. Solution: allocate on heap: char* get_city_name(double latitude, double longitude) { char* city_name = (char*)malloc(100); … return city_name; }

Common C Pitfalls (2) What’s wrong and how to fix it? char* buf = (char*)malloc(32); strcpy(buf, argv[1]);

Common C Pitfalls (2) Problem: Buffer overflow Solution: int buf_size = 32; char* buf = (char*)malloc(buf_size); strncpy(buf, argv[1], buf_size); Are buffer overflow bugs important? Buffer overflows lead to a lot of security exploits – check out Yoshi’s 484 class.

Common C Pitfalls (3) What’s wrong and how to fix it? char* buf = (char*)malloc(32); strncpy(buf, “hello”, 32); printf(“%s\n”, buf); buf = (char*)malloc(64); strncpy(buf, “bye”, 64); free(buf);

Common C Pitfalls (3) Problem: Memory leak Solution: char* buf = (char*)malloc(32); strncpy(buf, “hello”, 32); printf(“%s\n”, buf); free(buf); buf = (char*)malloc(64); … Are memory leaks important? OS, web server, web browser, your projects?

Common C Pitfalls (4) What’s wrong (besides ugliness) and how to fix it? char foo[2]; foo[0] = ‘H’; foo[1] = ‘i’; printf(“%s\n”, &foo);

Common C Pitfalls (4) Problem: String is not NULL-terminated Solution: char foo[3]; foo[0] = ‘H’; foo[1] = ‘i’; foo[2] = ‘\0’; printf(“%s\n”, &foo); Or, “more better”: char * foo = “Hi”; Double-quoted string literal syntax gets NULL- terminated automatically. Ask after: ------------- How are things different in Java? Are strings null-terminated? why do they not have to be? What’s anther approach? What’s the bug in all previous examples? Should check return value of malloc

Java programmer gotchas (1) { int i for(i = 0; i < 10; i++) … NOT for(int i = 0; i < 10; i++)

Java programmer gotchas (2) Uninitialized variables catch with –Wall compiler option #include <stdio.h> int main(int argc, char* argv[]) { int i; factorial(i); return 0; }

Java programmer gotchas (3) Error handling No exceptions Must look at return values

C Preprocessor #define FIFTEEN_TWO_THIRTEEN \ "The Class That Gives CMU Its Zip\n" int main(int argc, char* argv[]) { printf(FIFTEEN_TWO_THIRTEEN); return 0; }

After the preprocessor (gcc –E) int main(int argc, char* argv) { printf("The Class That Gives CMU Its Zip\n"); return 0; }

Conditional Compilation #define CS213 int main(int argc, char* argv) { #ifdef CS213 printf("The Class That Gives CMU Its Zip\n"); #else printf("Some other class\n"); #endif return 0; }

After the preprocessor (gcc –E) int main(int argc, char* argv) { printf("The Class That Gives CMU Its Zip\n"); return 0; }