CSE 124 Discussion (10/3) C/C++ Basics

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

PRINCIPLES OF OPERATING SYSTEMS

Today s Learning Objectives

Class Information ANNOUCEMENTS

High Performance Programming Programming in C part 1

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Programming in C S c o t t S c h r e m m e r

CSCI 171 Chapter Outlines

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

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

Software Development With Emacs: The Edit-Compile-Debug Cycle

Subject: Fundamental of Computer Programming 2068

Lecture 03 Bits, Bytes and Data Types

Lectures 5-6: Introduction to C

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

File I/O. Arash Rafiey. November 7, 2017

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

EC 413 Computer Organization

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

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

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

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

Short Notes of CS201

Dynamic memory allocation

Final CSE 131B Spring 2004

CS11 Intro C++ Spring 2018 Lecture 1

CS201 - Introduction to Programming Glossary By

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

Programming in C First meeting Tiina Niklander

Lectures 5-6: Introduction to C

Introduction to C An overview of the programming language C, syntax, data types and input/output

Processes. Johan Montelius KTH

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

just a ((somewhat) safer) dialect.

A process. the stack

CSE 351. GDB Introduction

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

Programming in C week 1 meeting Tiina Niklander

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

C programming basics T3-1 -

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

POINTER AND ARRAY SUNU WIBIRAMA

Programming in C First meeting

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Lab # 4. Files & Queues in C

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CS201 - Lecture 1 The C Programming Language

CS 61C: Great Ideas in Computer Architecture Introduction to C

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CSCI 2132 Final Exam Solutions

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

Lecture 3: C Programm

Memory Allocation in C

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

CS61, Fall 2012 Section 2 Notes

C Programming Lecture V

CS349/SE382 A1 C Programming Tutorial

Lecture 3. More About C

211: Computer Architecture Summer 2016

Programming in C. Pointers and Arrays

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

Programming in C. What is C?... What is C?

[0569] p 0318 garbage

CSE 333 Lecture 2 - arrays, memory, pointers

IV Unit Second Part STRUCTURES

Why VC++ instead of Dev C++?

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

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

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

8. Characters, Strings and Files

C Programming Review CSC 4320/6320

Introduction to the C Programming Language

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

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

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

Kurt Schmidt. October 30, 2018

JTSK Programming in C II C-Lab II. Lecture 3 & 4

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins)

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Reviewing gcc, make, gdb, and Linux Editors 1

CSE 333 Midterm Exam July 24, Name UW ID#

Chapter 11 Introduction to Programming in C

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

25.2 Opening and Closing a File

Tutorial 1 C Tutorial: Pointers, Strings, Exec

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

Recitation #11 Malloc Lab. November 7th, 2017

Motivation was to facilitate development of systems software, especially OS development.

LSN 3 C Concepts for OS Programming

CSC231 C Tutorial Fall 2018 Introduction to C

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

MPATE-GE 2618: C Programming for Music Technology. Syllabus

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

Final CSE 131B Spring 2005

Transcription:

CSE 124 Discussion (10/3) C/C++ Basics

Topics - main() function - Compiling with gcc/makefile - Primitives - Structs/Enums - Function calls/loops - C++ Classes/stdtl - Pointers/Arrays - Memory allocation/freeing - C vs C++ Strings - File I/O - GDB

Overview C was developed by Dennis Richie in AT&T Bell Labs -1972 C is a structured programming language. C enables modularity by breaking large file into smaller modules/blocks.

main() function main() is the entry point of every C program. Generally, the main() function will set up the environment and then call other functions/libraries that do the actual work. Every C/C++ program must have a main() function. The main() function supplies command line arguments via the argc and argv variables.

Compiling with gcc/makefile Makefiles are a simple way to organize code compilation. Individual C files can be compiled and executed as follows: gcc sample.c -o sample./sample For a group of files and headers you can compile the project by using a Makefile, and running the make command in your terminal. //Show code

Primitives Primitive types are the most basic types in C/C++. int, short, char, float, long, byte, are all primitive types. Pointers are a type that points to another type. The void type is special- it represents nothing.

Structs/Enums A struct in C is a collection of different data types called members. typedef struct Books { char title[50]; char author[50]; enum genre book_genre; int book_id; } book; Enums are explicitly named constants that can be used in other code. enum genre { Horror, //0 Fiction, //1 Drama //2 }; enum genre my_book_genre = Horror;

Function calls/loops 1 #include<stdio.h> 2 // function prototype, also called function declaration 3 float square ( float x ); 4 // main function, program starts from here 5 6 int main( ) 7 { 8 float m, n ; 9 printf ( "\nenter some number for finding square \n"); 10 scanf ( "%f", &m ) ; 11 // function call 12 n = square ( m ) ; 13 printf ( "\nsquare of the given number %f is %f",m,n ); 14 } 15 16 float square ( float x ) // function definition 17 { 18 float p ; 19 p = x * x ; 20 return ( p ) ; 21 } // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("enter a positive integer: "); scanf("%d", &num); // for loop terminates when n is less than count for(count = 1; count <= num; ++count) { sum += count; } } printf("sum = %d", sum); return 0; // Program to find factorial of a number // For a positive integer n, factorial = 1*2*3...n #include <stdio.h> int main() { int number; long long factorial; printf("enter an integer: "); scanf("%d",&number); factorial = 1; // loop terminates when number is less than or equal to 0 while (number > 0) { factorial *= number; // factorial = factorial*number; --number; } printf("factorial= %lld", factorial); return 0; }

C++ classes/stdtl The C++ standard library includes many classes that can be useful. This includes strings, thread objects, and more! You re allowed to use any classes in the standard C++ library, provided it doesn t violate other project restrictions. http://www.cplusplus.com/reference/

Pointers In C/C++, everything has a memory address. A memory address of an object is called a pointer to that object. Pointer types are denoted with the * character. You can get the pointer of any object by using the & character in front of it, and the data at a pointer by using the * character: int some_val = 5; int* pointer_to_some_val = &val; int the_value_of_some_val = *pointer_to_some_val;

Arrays In C/C++, an arrays and pointers are interchangable. An array is really just a pointer to a bunch of objects: int my_ints[5]; // typeof(my_ints) == (int*) int* pointer_to_elem = &my_ints[2]; *(pointer_to_elem + 1) == my_ints[3] == *(my_ints + 3); // true my_ints + 2 == pointer_to_elem // also true

Memory allocation/freeing In C, memory can be allocated in two ways: 1. Static Memory: Here you need to define the memory size on declaration. This is allocated on the program stack. 2. Dynamic Memory: Here you can allocate/reallocate/free memory during runtime. This is allocated on the program heap.

Stack vs Heap In C/C++, memory can be allocated in two places: the stack and the heap. The stack contains all of the program code and variables that are defined in a function. The heap can only be accessed by system calls such as malloc that request a memory allocation from the OS. Heap memory must be explicitly given back to the OS via a free system call. In C++, you can malloc memory using the new operator, and free it with del : SomeClass new_object = new SomeClass(...); del new_object;

C vs C++ strings In C, there is no string data type. A string is just an array of characters: char* some_str = Hello, world! ; Strings in C are null-terminated, which means the last character of the char array is the null byte, \0. This is to let functions know when the string actually ends! In C++, there is a string type in the std library. This is just a wrapper around C strings with some fancy functions. You can access the character array with the c_str() function: std::string another_str = Hey, everyone! ; char* the_real_str = another_str.c_str();

File I/O File operations: 1. Open a file : FILE pointer_name = fopen ("file_name", "Mode"); 2. Close a file : fclose(fp); 3. Reading a file : fscanf(fp, "%s", buffer) // read a string from the file until whitespace is encountered; 4. Writing to a file : fputc(ch, fp); // likewise fprintf can be used to write in the file. Modes: Mode r : It is a read only mode, Mode w : It is a write only mode Mode a : Using this mode Content can be appended

GDB GDB is a debugger by GNU project, it helps in checking the flow of the code line by line. All program to be debugged in gdb must be compiled by gcc with the option "-g" turning on Start GDB (garbage) Run program (args if any) Break execution Single step execution Print variable gdb./garbage (gdb) run arg_1 arg_2 break source_filename:line_number (gdb) break garbage.c:8 Breakpoint 1 at 0x1f7b: file garbage.c, line 8. (gdb) s (gdb) n n: the debugger will step to the next source line. Each function call will be treat as a single source code line. print variable_name (gdb) print a $10 = 88

Additional Resources Linux man (short for manual ) pages have pages for most of the ANSI/ISO C functions. You can read these online at https://linux.die.net/man/ The C++ Standard Library can be useful: http://www.cplusplus.com/reference/ SoloLearn has a C++ tutorial: https://www.sololearn.com/course/cplusplus/