1/15/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 11 (C-5)

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Dynamic Memory Allocation
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
System Files and Process Environment Password file Group file System identification Time Process environment.
Kernighan/Ritchie: Kelley/Pohl:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Introduction to C Programming CE Lecture 18 Dynamic Memory Allocation and Ragged Arrays.
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.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
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.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
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
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
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.
Introduction to Programming 3D Applications CE Lecture 12 Structure Pointers and Memory Management in C.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
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:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Review 1 List Data Structure List operations List Implementation Array Linked List.
ECE Application Programming
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Pointers *, &, array similarities, functions, sizeof.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Interacting with Unix. Getting the Process ID u Synopsis #include pid_t getpid(void); u Example: #include int main(){ pid_t n = getpid(); printf("Process.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
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 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.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Week 9 - Wednesday.  What did we talk about last time?  structs.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Computer Science 516 Addressing Modes. Addressing modes are how our programs get to data Multiple addressing modes created for specific uses Function.
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.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSCI206 - Computer Organization & Programming
Lecture 6 C++ Programming
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
Dynamic Memory Allocation
Dynamic Memory Allocation
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Chapter 10-1: Dynamic Memory Allocation
C Structures and Memory Allocation
Dynamic Memory – A Review
Presentation transcript:

1/15/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 11 (C-5)

1/15/2016Course material created by D. Woit 2 Functions and Structures We can pass a structure to a function: func1(woit); call by value as always (not modified) func1 makes a *copy* of car woit /*Source: struct5.c*/ #include struct complex { int r; int i; }; void WriteSum(struct complex c1, struct complex c2); int main(void) { struct complex A1, A2; A1.r = 4; A1.i = 7; A2.r = 3; A2.i = -1; WriteSum(A1,A2); return 0; } void WriteSum(struct complex c1, struct complex c2) { printf("%d + %di\n", (c1.r)+(c2.r), (c1.i)+(c2.i)); }

1/15/2016Course material created by D. Woit 3 Returning a structure to a calling program /*Source: struct6.c*/ #include struct complex { int r; int i; } ; struct complex ReadIt(void); int main(void) { struct complex X; X=ReadIt(); printf("%d + %di\n",X.r, X.i); return 0; } struct complex ReadIt() { struct complex temp; scanf("%d %d", &temp.r, &temp.i); return(temp); } data from temp *copied* into storage set aside for X

1/15/2016Course material created by D. Woit 4 HMWK Rewrite the above programs using typedefsfor complex numbers. Put functions WriteSum and MakeComplex, (along with anything else necessary)into a file called cmplx.c that can be compiled separately. Write a header file cmplx.h A program similar to this should then work (try it): #include "cmplx.h" void main(void) { complex X,Y; X=MakeComplex(1,2); Y=MakeComplex(3,4); WriteSum(X,Y); }

1/15/2016Course material created by D. Woit 5 Pointers to Structures In the example below pointer p point to the structure c1. With pointer, structure can be accessed in two ways: struct complex { int r; int i; } c1, *p; p=&c1; (*p).r = 4; //or p->r = 4; We can pass pointers to structures to functions instead of actual structure 1. to change value of structure inside function 2. saves execution time since structures could be hundreds of bytes long while a ptr is usually 4 bytes (if just pass structure, a *copy*of it must be made--time consuming)

1/15/2016Course material created by D. Woit 6 Example of pointer to structures Note ReadIt and WriteIt print using different syntax because ReadIt has POINTER to complexi, but WriteIt has complex. /*Source: struct8.c*/ #include struct complex { int r; int i; }; void ReadIt(struct complex *c); void WriteIt(struct complex p);

1/15/2016Course material created by D. Woit 7 Struct8.c int main(void) { struct complex A1, A2; ReadIt(&A1); WriteIt(A1); ReadIt(&A2); WriteIt(A2); return 0; } void ReadIt(struct complex *c) { printf("Enter complex: "); scanf("%d %d",&(c->r), &(c->i)); printf("Read %d + %di\n",c->r, c->i); } void WriteIt(struct complex c) { printf("Write: %d + %di\n", c.r, c.i); }

1/15/2016Course material created by D. Woit 8 Struct9.c /*Source: struct9.c*/ #include struct complex { int r; int i; }; void ScalarMult(int i, struct complex *p); void PrintComplex(struct complex *p); int main(void) { struct complex C={4,-2}; ScalarMult(3,&C); PrintComplex(&C); return 0; }

1/15/2016Course material created by D. Woit 9 Struct9.c void ScalarMult(int m, struct complex *p) { //pointer is required since mutating p p->r = p->r * m; p->i = p->i * m; } void PrintComplex(struct complex *c){ //pointer unnecessary since not mutating p //printf("%d + %di\n", c->r, c->i); printf("%d + %di\n", (*c).r, (*c).i); }

1/15/2016Course material created by D. Woit 10 HMWK rewrite the above program using typedefs for complex. Write ConjugateComplex which turns a complex number into its conjugate (imaginary part multiplied by -1). Write a function called NegComplex turns a complex number into its negative (both imaginary and real parts multiplied by -1.

1/15/2016Course material created by D. Woit 11 C's Time and Date Functions use Structures use structures to hold info defined in structure tm in struct tm { int tm_sec; /*seconds, 0-59*/ int tm_min; /*minutes, 0-59*/ int tm_hour; /*hours, 0-23*/ int tm_mday; /*day of month, 0-31*/ int tm_mon; /*months since Jan, 0-11*/ int tm_year; /*years since 1900*/ int tm_wday; /*days since Sunday 0-6*/ int tm_yday; /*days since Jan 1, 0-365*/ int tm_isdst; /*daylight savings time flag*/ }; struct tm *localtime(time_t *time); time_t time(time_t *time1);

1/15/2016Course material created by D. Woit 12 Example tm1.c /*Source: tm1.c Purpose: to display current system time and date */ #include void main(void) { struct tm *systime; time_t t; t = time(NULL); systime = localtime(&t); printf("Time is %d:%d:%d\n", systime->tm_hour, systime->tm_min, systime->tm_sec); printf("Date is %d/%d/%d\n", systime->tm_mon+1, systime->tm_mday, systime- >tm_year+1900); }

1/15/2016Course material created by D. Woit 13 System structures C has many other structures to give programmer access to system information. e.g., dirent.h lets you access the linux filesystem (files, dirs, their perms, etc.)

1/15/2016Course material created by D. Woit 14 Nested Structures struct evaluation { int tests; /*number of tests*/ int exam; /*non-0=yes, 0=no*/ int assigns; /*number of*/ int labs; /*number of*/ }; struct class { char CourseNum[10]; /*e.g., CPS393 */ char CourseName[80]; /*e.g., Intro to C & UNIX */ struct evaluation eval; /*eval info*/ } c1, c2[10]; c1.eval.assigns = 3; c2[0].eval.labs=6;

1/15/2016Course material created by D. Woit 15 Dynamic Memory Allocation In C we can allocate and free storage at run-time (DMA) v.s. compile-time as we have done so far calloc(NumItems, ItemSize); NumItems: number of items of storage requested ItemSize: size of each item (in bytes) calloc returns void (generic) pointers. must *cast* to desired type (ptr to NumItems x ItemSize bytes of memory) storage is initialized to zeros

1/15/2016Course material created by D. Woit 16 Dynamic Memory Allocation malloc(Size); Size: number of bytes storage not initialized e.g., to reserve an area for n integers

1/15/2016 Course material created by D. Woit 17 /*source: trycalloc.c */ #include int main(void) { int n; /*num elts of future array*/ int *p, *tmp; /*pointers to the future array*/ scanf("%d",&n); int i; p = (int *) calloc (n, sizeof(int)); if (p == NULL) { perror("calloc"); exit(0);} tmp = p; /* tmp is used to point to elements while p point to the beginning of the array */ /*load array with 0,1,2,...(n-1) */ for (i=0; i<n; i++) *tmp++ = i; //tmp[i]=i; //same for (i=0; i<n; i++) printf("p[%d] is %d\n",i,p[i]); /* or tmp = p; for (i=0; i<n; i++) printf("p[%d] is %d\n",i,*tmp++); */ exit(1); }

1/15/2016Course material created by D. Woit 18 Releasing the memory When memory no longer needed, free it for later use. When pgm ends, all dynamically allocated memory is freed, but if no longer needed *during* pgm execution, could free it immediately to release storage A long-running program, like the linux operating system itself must always free its memory, or eventually lots of unused, but unavailable memory around (full kidneys) free(p); Can dynamically allocate strings similarly. Since char is always 1 byte didn't do sizeof(char)

1/15/2016Course material created by D. Woit 19 Stralloc.c /*source: stralloc.c*/ #include #define MAX 10 int main(void){ char *A; int max_int=0; //need to add error-checking printf("enter max string length: "); scanf("%d",&max_int); while ((getchar())!='\n'); A=(char *)malloc(max_int+1); //room for null char printf("enter string: "); fgets(A,max_int,stdin); printf("Third char is: %c\n",*(A+2)); exit(0); }

1/15/2016Course material created by D. Woit 20 HMWK read about malloc and calloc (text, man pages). What do they return if no storage left to allocate (i.e., if they fail)? Write a program that reads an input file such as: The first integer, call it n, is the number of complex numbers to follow. The n complex numbers are then listed. Your program must dynamically allocate enough memory to store the array of n complex numbers.

1/15/2016Course material created by D. Woit 21 HMWK cont Complex numbers must be stored in a structure. (So you have an array of structures.) Then your program should loop through the array from end to front, and print out the complex numbers in it. E.g., your output should look like 8 + 2i i i 1 + 5i on stdout.

1/15/2016Course material created by D. Woit 22