Week 7 - Monday.  What did we talk about last time?  Pointers to pointers  Lab 6.

Slides:



Advertisements
Similar presentations
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Advertisements

Dynamic memory allocation
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
Week 5 - Wednesday.  What did we talk about last time?  Arrays.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters 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.
Outline Midterm results Static variables Memory model
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Week 7 - Wednesday.  What did we talk about last time?  scanf()  Memory allocation  malloc()  free()
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.
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.
Object-Oriented Programming in C++
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
(9-1) Strings I H&K Chapter 8 Instructor - Andrew S. O’Fallon CptS 121 (October 19, 2015) Washington State University.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CSCI 130 More on Arrays. Multi-dimensional Arrays Multi - Dimensional arrays: –have more than one subscript –can be directly initialized –can be initialized.
Department of Electronic & Electrical Engineering IO reading and writing variables scanf printf format strings "%d %c %f"
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Week 5 - Monday.  What did we talk about last time?  Processes  Lab 4.
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.
Chapter 7 Continued Arrays & Strings. Arrays of Structures Arrays can contain structures as well as simple data types. Let’s look at an example of this,
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Sections Basic Data Structures. 1.5 Data Structures The way you view and structure the data that your programs manipulate greatly influences your.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Computer Science 210 Computer Organization
Day 03 Introduction to C.
Storage Management.
Day 03 Introduction to C.
Dynamic Memory Allocation
Computer Science 210 Computer Organization
EECE.2160 ECE Application Programming
Chapter 16 Pointers and Arrays
C Programming Lecture-8 Pointers and Memory Management
Dynamic Memory – A Review
Presentation transcript:

Week 7 - Monday

 What did we talk about last time?  Pointers to pointers  Lab 6

Don’t worry if it doesn’t work right. If everything did, you’d be out of a job. Mosher’s Law of Software Engineering Don’t worry if it doesn’t work right. If everything did, you’d be out of a job. Mosher’s Law of Software Engineering

 So far, we have only talked about using getchar() (and command line arguments) for input  As some of you have discovered, there is a function that parallels printf() called scanf()  scanf() can read strings, int values, double values, characters, and anything else you can specify with a % formatting string int number; scanf("%d", &number); int number; scanf("%d", &number);

 In the first place, you have to use pointers (or at least the reference operator & )  I wanted you to understand character by character input (with getchar() ) because sometimes that's the best way to solve problems  Indeed, scanf() is built on character by character input  Crazy things can happen if scanf() is used carelessly

 These are mostly what you would expect, from your experience with printf() SpecifierType %dint %uunsigned int %o %x unsigned int (in octal for o or hex for x ) %dhshort %cchar %s null-terminated string %ffloat %fldouble %fLlong double

#include int main () { char name[80]; int age; int number; printf("Enter your name: "); scanf("%s",name); printf("Enter your age: "); scanf("%d",&age); printf("%s, you are %d years old.\n",name,age); printf("Enter a hexadecimal number: "); scanf("%x",&number); printf("You have entered 0x%08X (%d)\n",number,number); return 0; } #include int main () { char name[80]; int age; int number; printf("Enter your name: "); scanf("%s",name); printf("Enter your age: "); scanf("%d",&age); printf("%s, you are %d years old.\n",name,age); printf("Enter a hexadecimal number: "); scanf("%x",&number); printf("You have entered 0x%08X (%d)\n",number,number); return 0; }

 scanf() returns the number of items successfully read  Typically, scanf() is used to read in a single variable, making this value either 0 or 1  But it can also be used to read in multiple values int value1, value2, value3; int count = 0; do { printf("Enter three integers: "); count = scanf("%d %d %d",&value1, &value2, &value3); } while( count != 3 ); int value1, value2, value3; int count = 0; do { printf("Enter three integers: "); count = scanf("%d %d %d",&value1, &value2, &value3); } while( count != 3 );

 Functions can return pointers  If you get a pointer back, you can update the value that it points to  Pointers can also be used to give you a different view into an array char* moveForward(char* string) { return string + 1; } char* moveForward(char* string) { return string + 1; } char* word = "pig feet"; while( *word ) { printf("%s\n", word); word = moveForward( word ); } char* word = "pig feet"; while( *word ) { printf("%s\n", word); word = moveForward( word ); }

 Unfortunately, you can't return a pointer to a local variable  Well, you can, but it would be crazy  It would be pointing to a value that is no longer on the stack  Maybe it's still there…  But the next time a method is called, it could be blown away

int* getPointer() { int value = 5; int* pointer = &value; return pointer; } int* getPointer() { int value = 5; int* pointer = &value; return pointer; } int* p = getPointer(); getPointer pointer value main p p p p After return

 Memory can be allocated dynamically using a function called malloc()  Similar to using new in Java or C++  #include to use malloc()  Dynamically allocated memory is on the heap  It doesn't disappear when a function returns  To allocate memory, call malloc() with the number of bytes you want  It returns a pointer to that memory, which you cast to the appropriate type int* data = (int*)malloc(sizeof(int));

 Any single variable can be allocated this way  But why would someone do that when they could declare the variable locally? int* number = (int*)malloc(sizeof(int)); double* value = (double*)malloc(sizeof(double)); char* c = (char*)malloc(sizeof(char)); *number = 14; *value = 3.14; *c = '?'; int* number = (int*)malloc(sizeof(int)); double* value = (double*)malloc(sizeof(double)); char* c = (char*)malloc(sizeof(char)); *number = 14; *value = 3.14; *c = '?';

 It is much more common to allocate an array of values dynamically  The syntax is exactly the same, but you multiply the size of the type by the number of elements you want int i = 0; int* array = (int*)malloc(sizeof(int)*100); for( i = 0; i < 100; i++ ) array[i] = i + 1; int i = 0; int* array = (int*)malloc(sizeof(int)*100); for( i = 0; i < 100; i++ ) array[i] = i + 1;

 Dynamically allocated memory sits on the heap  So you can write a function that allocates memory and returns a pointer to it int* makeArray( int size ) { int* array = (int*)malloc(sizeof(int)*size); return array; } int* makeArray( int size ) { int* array = (int*)malloc(sizeof(int)*size); return array; }

 strdup() is a function that  Takes a string (a char* )  Allocates a new array to hold the characters in it  Copies them over  Returns the duplicated string  Let's write our own with the following prototype char* new_strdup(char* source);

 C is not garbage collected liked Java  If you allocate something on the stack, it disappears when the function returns  If you allocate something on the heap, you have to deallocate it with free()  free() does not set the pointer to be NULL  But you can afterwards char* things = (char*)malloc(100); free(things); char* things = (char*)malloc(100); free(things);

 Who is supposed to call free() ?  You should feel fear in your gut every time you write a malloc()  That fear should only dissipate when you write a matching free()  You need to be aware of functions like strdup() that call malloc() internally  Their return values will need to be freed eventually  Read documentation closely  And create good documentation for any functions you write that allocate memory

 If you try to free something that has already been freed, your program will probably crash  If you try to free a NULL pointer, it doesn’t do anything  Life is hard

 Everything gets freed at the end of your program  So, you can just hope you don't run out of space  However, if you are constantly allocating things and never freeing them, you will run out of space

 Prompt the user for an integer giving the size of a list of numbers  Dynamically allocate an array of the appropriate size  Read each of the numbers into the array  Sort the array  Print it out

 Dynamic memory allocation examples  Dynamically allocating multi-dimensional arrays

 Keep reading K&R chapter 5  Keep working on Project 3