EL2310 Scientific Programming

Similar documents
EL2310 Scientific Programming

EL2310 Scientific Programming

PRINCIPLES OF OPERATING SYSTEMS

File IO and command line input CSE 2451

25.2 Opening and Closing a File

File Handling in C. EECS 2031 Fall October 27, 2014

CSC C69: OPERATING SYSTEMS

High Performance Programming Programming in C part 1

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CSC 1107: Structured Programming

CSC 1107: Structured Programming

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

ch = argv[i][++j]; /* why does ++j but j++ does not? */

211: Computer Architecture Summer 2016

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

C programming basics T3-1 -

Recitation 2/18/2012

Heap Arrays. Steven R. Bagley

Programming refresher and intro to C programming

Computers Programming Course 5. Iulian Năstac

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Contents. A Review of C language. Visual C Visual C++ 6.0

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

In the case of the dynamic array, the space must be deallocated when the program is finished with it. free(x);

Standard File Pointers

2009 S2 COMP File Operations

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Heap Arrays and Linked Lists. Steven R. Bagley

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

ECEN 449 Microprocessor System Design. Review of C Programming

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Final CSE 131B Spring 2004

Programming in C Quick Start! Biostatistics 615 Lecture 4

Course organization. Course introduction ( Week 1)

Today s Learning Objectives

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

OBJECT ORIENTED PROGRAMMING

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Stream Model of I/O. Basic I/O in C

Goals of this Lecture

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

CSE 333 Lecture 2 Memory

ENG120. Misc. Topics

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Process Management! Goals of this Lecture!

Kurt Schmidt. October 30, 2018

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

211: Computer Architecture Summer 2016

C-Refresher: Session 10 Disk IO

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

In Java we have the keyword null, which is the value of an uninitialized reference type

Understanding Pointers

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

EL2310 Scientific Programming LAB2: C lab session. Patric Jensfelt, Andrzej Pronobis

A Fast Review of C Essentials Part I

Lecture 3: C Programm

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Input / Output Functions

Computer Organization & Systems Exam I Example Questions

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

COMPSCI 210 Part II Data Structure

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

A brief introduction to C programming for Java programmers

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Memory Allocation in C

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

COMP 2355 Introduction to Systems Programming

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Lab # 4. Files & Queues in C


Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Dynamic memory allocation (malloc)

Lecture 8: Structs & File I/O

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

Lesson #8. Structures Linked Lists Command Line Arguments

Contents of Lecture 3

Organization of a file

C Language Programming

BLM2031 Structured Programming. Zeyneb KURT

CSE 374 Programming Concepts & Tools

Transcription:

Lecture 12: Memory, Files and Bitoperations (pronobis@kth.se)

Overview Overview Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations

Wrap Up Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations

Wrap Up Last time Complex data structures (struct) Memory

Wrap Up Today More on Memory Reading/writing files Bitwise operations

Wrap Up Pointers and structures You can use pointers to structures Ex: struct complex number x; struct complex number *xptr = &x; To access a member using a pointer we use the > operator Ex: xptr->real = 2; Same as (*xptr).real = 2; and x.real = 2;

Wrap Up Structures of structures You can have any number of levels of structures of structures Ex: struct position { double x; double y; }; struct line { struct position start; struct position end; };

Wrap Up Pointers to structures in structures Normally you need to declare a type before you use it. You can have a pointer to the structure you define Ex: struct person { char name[32]; struct person *parent; };

Wrap Up cast Some conversions between types are implicit Ex: double x = 4; (cast from int to double) In other cases you need to tell the compiler to do this Ex: int a = (int)4.2; (will truncate to 4) Often used together with pointers Ex: int a; unsigned char *byte = (unsigned char*)&a;

Wrap Up Dynamic allocation of memory Sometimes you do not know the size of arrays etc. Idea: Allocate memory dynamically This way you can allocate memory at runtime

Wrap Up malloc Allocate memory with malloc Need to #include<stdlib.h> This function returns a pointer of type void* Ex: int *p = malloc(100*sizeof(int)); To avoid warnings, add explicit cast Ex: int *p = (int *)malloc(100*sizeof(int)); Will allocate memory for 100 ints

Wrap Up free You should free the memory that you no longer need!!! Ex: int *p = (int *)malloc(100*sizeof(int));... free(p); If you do not free allocated memory you will get memory leaks Your program will crash eventually A big problem if you program should run a very long time

Wrap Up Memory When you run your program the memory is divided between the heap and the stack The stack: Memory allocated for all parameters and local variables of a function Fast-allocated memory Current function at the top of the stack When a function returns its memory is removed from the stack The heap: Used for persistent data Dynamically allocated memory From http://www.csl.mtu.edu/cs3090/www/lecture-notes/memory Allocation.ppt

Wrap Up Common mistakes Forgetting to free memory (memory leak!!!) Using memory that you have not initialized Using memory that you do not own Using more memory than you allocated Returning pointer to local variable (thus no longer existing)

Wrap Up Tip when using dynamic memory allocation If you have a malloc think about where the corresponding free is

Main function; reading and writing Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations

Main function; reading and writing Command line arguments You add parameters to the main function int main(int argc, char **argv) See the lab in C for more details and examples First argument is in argv[1], argv[0] contains program name atoi and atof are useful to get number from char arrays Ex: int value;... if (argc > 1) value = atoi(argv[1]); else value = 42;

Main function; reading and writing Reading and writing files We have already seen how we can write to the screen with printf This writes to a special file called stdout Can also write to stderr Ex: fprintf(stderr, Hello world\n );

Main function; reading and writing Reading from the keyboard Can use char getchar(); to get a single character For more more complex input try scanf(...) which is the dual of printf(...) The arguments for scanf the same as for printf except that it wants pointers to where to put the data Ex: int i; double num[3]; printf("enter 3 number: "); fflush(stdout); for (i = 0; i < 3; i++) { scanf("%lf", &num[i]); }

Main function; reading and writing Opening/closing a file FILE *fopen(char *path, char *mode); mode is r : read, w : write, a :append,... On success returns pointer to file descriptor, else NULL fclose(file*);

Main function; reading and writing Writing to a file Write to the file with for example fprintf(file*,...); Ex: double x=1, y=2, theta=0.5; FILE *fd = NULL; fd = fopen("test.txt", w ); fprintf(fd, "Robot pose is %f %f %f\n", x,y,theta); fclose(fd);

Main function; reading and writing Reading from a file Read from the file with for example fscanf(file*,...); Ex: double x,y,theta; FILE *fd = NULL; fd = fopen("test.txt", "r"); fscanf(fd, "Robot pose is %lf %lf %lf\n", &x,&y,&theta); fclose(fd); Notice that you need %lf when you read a double, %f for a float Function sscanf() is similar but operates on a char array instead of a file

Bitwise Operations Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations

Bitwise Operations Bitwise operations When programming at low level, bitwise operations are common Also, if you want to store flags it is very wasteful to use 1 byte for every flag that can only be 0 or 1. Typical construction, use bitmask Let each bit in the variable be one flag

Bitwise Operations Bitwise operator & bitwise AND bitwise inclusive OR ˆ bitwise exclusive OR << left shift >> right shift bitwise NOT

Bitwise Operations Example of bit operations mask = mask & 0xF Set all but the lower 4 bits to zero mask = mask 0x3 Set lower 2 bits short value;... unsigned char lower = (short & 0xFF); unsigned char upper = (short >> 8); What is printed? int x = 1, y = 2; if (x && y) printf("case 1\n"); if (x & y) printf("case 2\n");

Bitwise Operations Shift operators Should primarily be used on unsigned data types Shifting results in division (right) and multiplication (left) of integers by 2 times the number of shifts

Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations

Boids Simulate Flocking Invented by Craig Reynolds 1987 Based on very simple interaction rules

SDL - Simple DirectMedia Layer Open Source C library for, Graphics Sound Input

main 1. Define Variables 2. Initialise Screen to draw on 3. Event Loop 4. Cleans up

Event Loop Switch statement SDL KEYDOWN: if key is pressed, check if key is ESC SDL QUIT: Quit using system SDL MOUSEMOTION: If mose is moving FPS times per second call update boids() render screen(screen)

Skeleton int render screen(sdl Surface* screen); void update boids(void); void clean up(sdl Surface* screen); void read mouse(sdl Event* event); void put pixel(sdl Surface* screen,int x,int y,pixel* p); void clear screen(sdl Surface* screen); void render boids(void);

int render screen(sdl Surface* screen); 1. Creates a white pixel 2. SDL LockSurface(screen);: Opens the screen for rendering 3. SDL UnlockSurface(screen);: Closes the screen 4. You can only safely write to the screen between these commands

void read mouse(sdl Event* event); Called if mouse movement triggered Prints out mouse pointer coordinates

Think through how to structure data structs structs of structs... How should the flow of the program be Divide into several functions Comment code for someone else to understand Base program is NOT the only solution