CS 241 Section Week #2 2/4/10. 2 Topics This Section MP1 overview Part1: Pointer manipulation Part2: Basic dictionary structure implementation Review.

Slides:



Advertisements
Similar presentations
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
Chapter Fourteen Strings Revisited. Strings A string is an array of characters A string is a pointer to a sequence of characters A string is a complete.
Pointers in C Rohit Khokher
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
1 C-strings String = null-terminated array of characters The null character ('\0') specifies where the string terminates in memory. Example: The string.
C strings (Reek, Ch. 9) 1CS 3090: Safety Critical Programming in C.
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Introduction to C programming
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
String Library Calls (Representative, not Exhaustive) Rudra Dutta CSC Spring 2007, Section 001.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
CS 241 Section Week #2 9/9/10. 2 Topics This Section MP1 issues MP2 overview Process creation using fork()‏ Debugging tools: valgrind, gdb.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Charles Clute Tom Most Michael Hein. Strings in C  There is no String... But there’s hope! Strings are character arrays char volume[6]; char volume[6]
5.6 String Processing Part 2. Sprintf(destnvar,…..regularprintf) Write formatted data to string Same as printf except the output is put in variable. A.
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
Topics This Section  More C basics  Strings  Functions  Structures  Memory.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
1 Unix system calls fork( ) wait( ) exit( ). 2 How To Create New Processes? n Underlying mechanism -A process runs fork to create a child process -Parent.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
C Programming Tutorial – Part I
2016.
CSCI206 - Computer Organization & Programming
Programming Languages and Paradigms
Lecture 6 C++ Programming
CS1100 Computational Engineering
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Chapter 16 Pointers and Arrays
C++ Pointers and Strings
TUTORIAL 7 CS 137 F18 October 30th.
C++ Pointers and Strings
Dynamic Memory – A Review
Presentation transcript:

CS 241 Section Week #2 2/4/10

2 Topics This Section MP1 overview Part1: Pointer manipulation Part2: Basic dictionary structure implementation Review of strings Memory allocation and free Process creation using fork()‏

3 MP1 part1: Pointers mp1-functions.c contains 12 different functions, each of which print out “Illinois” Edit part1.c to print out 12 "Illinois" lines To print a "Illinois" line, formulate the parameter(s) to the corresponding function appropriately Do NOT modify mp1-functions.c

4 Review of Pointers The & operator creates a pointer to a variable int x; int *xptr = &x; // xptr = 0xAF981DF8 The * operator reads the data which a pointer references int y = *xptr; // y = x

5 Pointer arithmetic char a[8]; /* array of bytes */ char *p = a; /* p, a: 0xAF99EFDC */ char *q = a+3; /* q: 0xAF99EFDF */ ( a+3 and &a[3] are the same )‏...

6 Pointer arithmetic (2)‏ int b[2]; /* array of 4-byte words */ int *q = b+1; /* q: 0xAF99EFE0 */ char *r = &b[1]; /* r: 0xAF99EFE0 */...

7 MP1 part2: Dictionary data structure Implement a basic dictionary data structure Defined in libdictionary/libdictionary.h typedef struct _dictionary_t{ char *key, *value; struct _dictionary_t *next; } Host: key = Host value =

8 Dictionary files part2.c – Provides a simple program to populate the dictionary from a file libdictionary/libdictionary.h – Contains definition of the dictionary data structure ( struct dictionary_t ) and its six functions libdictionary/libdictionary.c – Implement the functions here

9 Dictionary functions int dictionary_init(dictionary_t *d)‏ int dictionary_add(dictionary_t *d, char *key, char *value)‏ void dictionary_remove(dictionary_t *d, char *key)‏ int dictionary_parse(dictionary_t *d, char *key_value)‏ void dictionary_print(dictionary_t *d)‏ void dictionary_destroy(dictionary_t *d)‏

10 Dictionary functions int dictionary_init(dictionary_t *d)‏ – Initialize data structure `d` – Return value 0: if initialization successful Non-zero integer: otherwise int dictionary_destroy(dictionary_t *d)‏ – Remove all entries from `d` (uses dictionary_remove function)‏ – Free up any other memory associated with `d`

11 Dictionary functions int dictionary_add(dictionary_t *d, char *key, char *value)‏ – add (key, value) pair to dictionary `d` – DO NOT edit `d` if the key already exists – Return value non-zero integer: if key already exists 0: otherwise – Make a copy of the strings `key` and `value` before adding them to `d`

12 Dictionary functions void dictionary_remove(dictionary_t *d, char *key)‏ – remove (key, value) pair from dictionary `d` if key exists – Free the memory allocated during dictionary_add function call

13 Dictionary functions int dictionary_parse(dictionary_t *d, char *key_value)‏ Parameter key_value will be formatted as an HTTP header ( key_field: value_field )‏ Add ( key_field, value_field ) pair to `d` using dictionary_add(... )‏ Return value – Non-zero integer: If key_value does not comply with the format or if the call to dictionary_add(... ) fails – 0: otherwise

14 Dictionary functions void dictionary_print(dictionary_t *d)‏ – Print out the entire contents of the dictionary `d` – Print out format printf("%s: %s", key, value); where key and value are variables storing the ( key, value ) pair of the entry

15 Review of Strings

16 Strings Sequence of zero or more characters, terminated by NULL char m[10] = “dog”; 10 bytes are allocated for array `m` Array `m` is initialized as char m[10] = {'d', 'o', 'g', '\0'};

17 String manipulation functions #include at program start Some useful functions strlen strcpy, strcat strcmp strstr

18 String Length size_t strlen(char *str)‏ Returns the length of the string size_t is an unsigned integer type, used to define sizes of strings and (other) memory blocks String length does not include NULL char m[10] = “dog”; int len = strlen(m); // we get len = 3

19 String Initialization char *strcpy(char *dst, char const *src)‏ char *strcat (char *dst, char const *src)‏ Write src string to some dst location Make sure: dst string is large enough to hold result (including NULL at the end)‏ src, dst regions do NOT overlap (undefined behavior in this case)‏ char m[10] = “dog”; strcpy(m+1, m);

20 String Comparison int strcmp(char const *s1, char const *s2)‏ Compares the string values of s1 and s2 lexicographically Return Value Less than 0: if s1 precedes s2 0: if s1 and s2 value are equal Greater than 0: if s1 follows s2

21 String searching char *strstr(const char *haystack, const char *needle)‏  Returns a pointer to the first occurrence of substring needle in the string haystack  Returns NULL if the substring needle is not found

22 Memory Allocation and Free

23 Memory Allocation void * malloc ( size_t size )‏ void *free(void *ptr)‏ Cast the allocated memory to appropriate type before using it char *s = (char*)malloc(1024*sizeof(char)); You can only free memory which is allocated using malloc(... )‏

24 Using valgrind to check memory leak To run a program (./part1 )‏ To use valgrind ( valgrind –-leak- check=full./part1 )‏ valgrind output with no memory leak ==19376== ERROR SUMMARY: 0 errors from 0 contexts... ==19376== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.... ==19376== All heap blocks were freed -- no leaks are possible.

25 valgrind output with memory leak Memory is allocated using malloc(... ) inside the function testmalloc(... )‏ ==20086== ERROR SUMMARY: 1 errors from 1 contexts... ==20086== malloc/free: 1 allocs, 0 frees, 10 bytes allocated.... ==20086== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==20086== at 0x4022AB8: malloc (vg_replace_malloc.c:207)‏ ==20086== by 0x : testmalloc (in /home/farhana/test)‏ ==20086== by 0x804848A: main (in /home/farhana/test)‏... ==20086== LEAK SUMMARY: ==20086== definitely lost: 10 bytes in 1 blocks....

26 Processes

27 Process creation using fork()‏ A process is an instance of a running program fork() creates a new process – In parent, fork() returns child pid – In child, fork() returns 0 The child process is identical to the parent process, except: – Process ID ( getpid() )‏ – Parent ID ( getppid() )‏

28 fork() example #include int main() { pid_t child_pid = fork(); if (child_pid < 0) {// error code perror(“Fork Failed”); return –1; } printf(“I'm process %d\n”,getpid()); if (child_pid == 0) {// child code printf(”I’m the child of parent process %d\n”, getppid()); } else { /* child_pid > 0 */// parent code printf(“I’m the parent of child process %d\n”, child_pid); } return 0; }