Week 7 - Wednesday.  What did we talk about last time?  scanf()  Memory allocation  malloc()  free()

Slides:



Advertisements
Similar presentations
Memory Management Chapter FourteenModern Programming Languages, 2nd ed.1.
Advertisements

CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
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.
An introduction to pointers in c
Dynamic Memory Allocation I Topics Basic representation and alignment (mainly for static memory allocation, main concepts carry over to dynamic memory.
Kernighan/Ritchie: Kelley/Pohl:
Week 7 - Friday.  What did we talk about last time?  Allocating 2D arrays.
Week 7 - Wednesday.  What did we talk about last time?  Transparency  Gamma correction  Started texturing.
Week 7 - Monday.  What did we talk about last time?  Pointers to pointers  Lab 6.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
 Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises:
An Introduction to Programming with C++ Fifth Edition
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
CIS 101: Computer Programming and Problem Solving Lecture10 Usman Roshan Department of Computer Science NJIT.
© 2006 Pearson Addison-Wesley. All rights reserved6-1 More on Recursion.
CS61C L06 C Memory Management (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
Arrays Ethan Cerami New York University Today n Array Basics (Review) n Random Number Example n Passing Arrays to Functions n Strings.
CS 117 Spring 2002 April 5, Exam 3 April 10 –files, arrays, strings, classes –practice exams are up –review on Monday.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
C Slides and captured lecture (video and sound) are available at:
Pointers Applications
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Simulated Pointers Limitations Of Java Pointers May be used for internal data structures only. Data structure backup requires serialization and deserialization.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Homework due Test the random number generator Create a 1D array of n ints Fill the array with random numbers between 0 and 100 Compute and report the average.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
ECE Application Programming
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Dynamic Memory Allocation II
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
1D Arrays and Random Numbers Artem A. Lenskiy, PhD May 26, 2014.
UNIT 11 Random Numbers.
CSCI 156: Lab 11 Paging. Our Simple Architecture Logical memory space for a process consists of 16 pages of 4k bytes each. Your program thinks it has.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Simulated Pointers Limitations Of C++ Pointers May be used for internal data structures only. Data structure backup requires serialization and deserialization.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Revision. Generating a pseudo-random number Necessary libraries: and Seeding: srand(time(NULL))  We set the seed based on the current time  NB! Time-dependent.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Chapter 9: Value-Returning Functions
Functions, Part 2 of 2 Topics Functions That Return a Value
Number guessing game Pick a random number between 1 and 10
CS1010 Programming Methodology
CSCI206 - Computer Organization & Programming
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Revision.
Assignment Operators Topics Increment and Decrement Operators
Week 7 - Friday CS222.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Week 7 - Wednesday

 What did we talk about last time?  scanf()  Memory allocation  malloc()  free()

Beware of bugs in the above code; I have only proved it correct, not tried it. Donald E. Knuth Beware of bugs in the above code; I have only proved it correct, not tried it. Donald E. Knuth

 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

 Let's see this in action  Can we make it more interesting?  Could we discover how much heap space we have?  Try a binary search char* buffer; while( 1 ) { buffer = (char*)malloc(100); buffer[0] = 'a'; } char* buffer; while( 1 ) { buffer = (char*)malloc(100); buffer[0] = 'a'; }

 We know how to dynamically allocate a regular array  How would you dynamically allocate a 2D array?  In C, you can't do it in one step  You have to allocate an array of pointers  Then you make each one of them point at an appropriate place in memory

 One way to dynamically allocate a 2D array is to allocate each row individually  When finished, you can access table like any 2D array int** table = (int**)malloc(sizeof(int*)*rows); int i = 0; for( i = 0; i < rows; i++ ) table[i] = (int*)malloc(sizeof(int)*columns); int** table = (int**)malloc(sizeof(int*)*rows); int i = 0; for( i = 0; i < rows; i++ ) table[i] = (int*)malloc(sizeof(int)*columns); table[3][7] = 14;

table Chunks of data that could be anywhere in memory

 To free a 2D array allocated with the Ragged Approach  Free each row separately  Finally, free the array of rows for( i = 0; i < rows; i++ ) free( table[i] ); free( table ); for( i = 0; i < rows; i++ ) free( table[i] ); free( table );

 Alternatively, you can allocate the memory for all rows at once  Then you make each row point to the right place  When finished, you can still access table like any 2D array int** table = (int**)malloc(sizeof(int*)*rows); int* data = (int*)malloc(sizeof(int)*rows*columns); int i = 0; for( i = 0; i < rows; i++ ) table[i] = &data[i*columns]; int** table = (int**)malloc(sizeof(int*)*rows); int* data = (int*)malloc(sizeof(int)*rows*columns); int i = 0; for( i = 0; i < rows; i++ ) table[i] = &data[i*columns]; table[3][7] = 14;

table Contiguously allocated memory

 To free a 2D array allocated with the Contiguous Approach  Free the big block of memory  Free the array of rows  No loop needed free( table[0] ); free( table ); free( table[0] ); free( table );

RAGGED  Pros  Each row can be allocated and freed independently  Rows can be shuffled in order with only pointer changes  Rows can be different lengths  Cons  Fragmented memory  Less locality of reference  Requires a loop to free CONTIGUOUS  Pros  Better locality of reference  Can free the entire thing with two free() calls  Shuffling rows with pointers is possible, but you also have to keep track of the beginning  Cons  Large allocations are more likely to fail (out of memory)  Can't free individual rows

 C provides the rand() function in stdlib.h  rand() uses a linear congruential generator (LCG) to generate pseudorandom numbers  rand() generates an int in the range 0 to RAND_MAX (a constant defined in stdlib.h )

 If you want values between 0 and n (not including n ), you usually mod the result by n //dice rolls int die = 0; int i = 0; for( i = 0; i < 10; i++ ) { die = rand() % 6 + 1; //[0,5] + 1 is [1,6] printf("Die value: %d\n", die); } //dice rolls int die = 0; int i = 0; for( i = 0; i < 10; i++ ) { die = rand() % 6 + 1; //[0,5] + 1 is [1,6] printf("Die value: %d\n", die); }

 Every time I run the program, I get the same sequence of random numbers  Pseudorandom, indeed!  This problem is fundamental to LCGs  The pseudorandom number generated at each step is computed by the number from the previous step  By default, the starting point is 1

 To overcome the problem, we call srand() which allows us to set a starting point for the random numbers  But, if I always start with 93, I'll still always get the same sequence of random numbers each time I run my program  I need a random number to put into srand()  I need a random number to get a random number? int random = 0; srand(93); random = rand(); //starts from seed of 93 int random = 0; srand(93); random = rand(); //starts from seed of 93

 Well, time changes when you run your program  The typical solution is to use the number of seconds since January 1, 1970 as your seed  To get this value, call the time() function with parameter NULL  You'll need to include time.h int die = 0; int i = 0; srand(time(NULL)); for( i = 0; i < 10; i++ ) { die = rand() % 6 + 1; //[0,5] + 1 is [1,6] printf("Die value: %d\n", die); } int die = 0; int i = 0; srand(time(NULL)); for( i = 0; i < 10; i++ ) { die = rand() % 6 + 1; //[0,5] + 1 is [1,6] printf("Die value: %d\n", die); }

 Include the following headers:  stdlib.h  time.h  Use rand() % n to get values between 0 and n – 1  Always call srand(time(NULL)) before your first call to rand()  Only call srand() once per program  Seeding multiple times makes no sense and usually makes your output much less random

 Dynamically allocate an 8 x 8 array of char values  Loop through each element in the array  With 1/8 probability, put a 'Q' in the element, representing a queen  Otherwise, put a ' ' (space) in the element  Print out the resulting chessboard  Use | and – to mark rows and columns  Print out whether or not there are queens that can attack each other

 Memory allocation from the system's perspective  Lab 7

 Read LPI chapter 7  Keep working on Project 3  Internship opportunity:  Naval Supply Systems Command  Student Trainee Position as Information Technology Specialist  For more information: ▪ 0