CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
C Lab 3 C Arraylist Implementation. Goals ●Review ○ Referencing/Dereferencing ○ Free ●realloc and memmove ●ArrayList ●Debugging with GDB.
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Informática II Prof. Dr. Gustavo Patiño MJ
Informationsteknologi Tuesday, September 18, 2007 Computer Systems/Operating Systems - Class 61 Today’s class Finish review of C Process description and.
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.
Informationsteknologi Friday, September 14, 2007Computer Systems/Operating Systems - Class 51 Today’s class Finish operating system overview Review of.
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’;
CSSE 332 Functions, Pointers in C. 2 Functions - why and how ? If a problem is large If a problem is large Modularization – easier to: Modularization.
CS 414/415 section C for Java programmers Indranil Gupta.
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.
Software Engineering Recitation 9 Suhit Gupta. Today C.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Day 01 Introduction to C. Saving Dyknow notes Save on the server. Can access from anywhere. Will have to install Dyknow on that machine. Must connect.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Why learn C (after Java)? Both high-level and low-level language Better control of low-level mechanisms Performance better than Java Java hides many details.
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Class 2 CSI2172
Outline Midterm results Static variables Memory model
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Stack and Heap Memory Stack resident variables include:
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C Programming Lecture 10-1 : Array & Pointer. Character Array String A sequence of characters The last character should be ‘\0’ that indicates “the end.
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.
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.
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Functions & Pointers in C Jordan Erenrich
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
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.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
CSE 333 – SECTION 2 Memory Management. Questions, Comments, Concerns Do you have any? Exercises going ok? Lectures make sense? Homework 1 – START EARLY!
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic memory allocation and Intraprogram Communication.
Angela Dalton (based on original slides by Indranil Gupta)
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
C Primer.
Day 03 Introduction to C.
Day 04 Introduction to C.
Day 03 Introduction to C.
Outline Defining and using Pointers Operations on pointers
7. Pointers, Dynamic Memory
C Programming Lecture-8 Pointers and Memory Management
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB

2 Example 11 #include int main(int argc, char *argv[]){ int *ptr; /* allocate space to hold an int */ ptr = (int*)malloc(4 * sizeof(int)); /* do stuff with the space */ *ptr=4; //ptr[0] = 4; /* free up the allocated space */ free(ptr); return 0; } Explicit memory allocation Explicit allocation and de-allocation Explicit allocation and de-allocation

3 int *ptr; ? ptr 4000 ptr = (int*)malloc(4 * sizeof(int)); ??? ? *ptr=4; 4 free(ptr); Explicit memory allocation

4 Dynamic array int *ptr, i,size; printf(“Enter the size of the array”); scanf(“%d”, &size) ptr = (int *) malloc( size * sizeof(int) ); for(i=0; i<size; i++){ ptr[i] = i; }

5 Array of Pointers Variable length strings Variable length strings /* card[4] => array of 4 elements char* => element is a pointer to a character. char* => element is a pointer to a character. *card[4] => array of 4 pointers */ *card[4] => array of 4 pointers */ char *card[4]; card[3]4012 card[2]4008 card[1]4004 card[0]4000 NULL

6 card[0] = (char*)malloc(6*sizeof(char)); card[1] = (char*)malloc(3*sizeof(char));... Static allocation of a 2D array: Static allocation of a 2D array: char card[4][10]; //waste of space Array of Pointers

7 Common errors - Memory leak int *ptr, x; //ptr points to newly allocated memory ptr = (int*)malloc(10*sizeof(int)); // ptr now points away from allocated memory // ptr now points away from allocated memory ptr = &x; Memory allocated with malloc is no longer available for use by the program. Memory allocated with malloc is no longer available for use by the program. Released only when program quits. Released only when program quits. Becomes a problem in large programs where a large number of variables are created and destroyed during the execution of the program. Becomes a problem in large programs where a large number of variables are created and destroyed during the execution of the program.

8 Common errors - Dangling pointers int *i, *x; i = (int*)malloc( 5 x sizeof(int)); x = i; //both point to the same address. /* both i and x are dangling pointers; trying to access either of them can cause logical errors */ either of them can cause logical errors */free(x); x = NULL; // One way to prevent incorrect access i = NULL;

9 Functions – pointers as arguments Example 12 #include int sumAndInc(int *pa, int *pb,int* pc); int main(int argc, char *argv[]){ int a=4, b=5, c=6; int *ptr = &b; /* call the function */ int total = sumAndInc(&a,ptr,&c); printf(“The sum of %d and %d is %d and c is %p\n”, a, b, total, c); } /* pointers as arguments */ int sumAndInc(int *pa, int *pb,int *pc ){ *pc = *pc+1; // return a pointee value; NOT *(pc+1) return (*pa+*pb); /* return by value */ }

10 a b c ptr In main() pa pb pc In function

11 a b c ptr In main() after the function call

12 What’s wrong with this ? Example 13 #include void DoSomething(int *ptr); int main(int argc, char *argv[]) { int *p; DoSomething(p); printf(“%d”, *p); /* will this work ? */ return 0; } /* passed and returned using pointers */ void DoSomething(int *ptr){ int temp= 5+3; ptr = &temp; } /* compiles correctly, but gives incorrect output */

13 p ? 4000 ptr 6000 ? temp In main() In the function

14 p ? 4000 In main() after the function call

int main(int argc, char *argv[]) { int *p; DoSomething( &p ); printf(“%d”, *p); /* will this work ? */ return 0; } /* passed and returned using pointers */ void DoSomething(int **ptr){ int temp= 8; int temp= 8; *ptr = (int*)malloc(sizeof(int)); *ptr = (int*)malloc(sizeof(int)); **ptr = temp; **ptr = temp;}

16 p ? 4000 ptr 6000 temp In main() In the function ? 8000 On the heap

17 p ? 4000 In main() In the function ? 8000 On the heap

18 Functions - Passing and returning arrays Example 14 #include void init_array( int array[], int size ) ; int main(int argc, char *argv[] ){ int list[5]; init_array(list, 5); //No & because list //is already an address for (i = 0; i < 5; i++) printf(“next:%d”, list[i]); } /* why size ? */ void init_array(int array[], int size) { /* arrays ALWAYS passed as pointers */ int i; for (i = 0; i < size; i++) array[i] = i; }

19 Passing/Returning a structure /* pass struct by value */ void displayYear_1(struct birthday mybday) { printf(“I was born in %d\n”, mybday.year); }/* - inefficient: why ? */ /* pass pointer to struct */ void displayYear_2(struct birthday *pmybday) { printf(“I was born in %d\n”, pmybday->year); /* Note: ‘->’, not ‘.’, after a struct pointer */ } /* return struct by value */ struct birthday get_bday(void){ struct birthday newbday; newbday.year=1971; /* ‘.’ after a struct */ return newbday; }/* - also inefficient: why ? */

20 GNU debugger (gdb) Tutorial and reference sheet on class website Tutorial and reference sheet on class website –…/Homework/Sec-01/gdbtutorial.htm –…/Homework/Sec-01/gdb-reference-card.pdf

Homework 4 and 5 More practice on C. More practice on C. Available on class’s Angel page Available on class’s Angel page – follow link from the schedule page 21