Dynamic memory allocation (malloc)
|
|
- Stanley Ball
- 5 years ago
- Views:
Transcription
1 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) p1-p2 p1<>!= p2 Array as function argument decay Pass sub_array Arrays of pointers Command line argument (program parameter) Pointer to arrays and two dimensional arrays Memory allocation Pointer to functions Pointer to structures IO Previous lecture
2 2 Problems with pointers int *ptr; /* I m a pointer to an int */ ptr= &a /*I got the address of rate */ *ptr = 5; /* set contents of the pointee a */ int *ptr; /* I m a pointer to an int */ *ptr = 5; /* contents of the pointee is 5*/ segmentation fault (core dumped) ptr is uninitialized. Has some random value but don t know Points to sth unknown, may be your OS! Always make it point to sth! How? 1) int a; ptr =&a; int arr[20]; ptr=arr; 2) ptr = ptr2 assuming ptr2 is good 3 3) ptr = malloc (...) Problems with pointers, another scenario char name[20]; char *name2; int age; double wage; scanf( %s %s %d %f,name,name2,age,wage); printf( input name, name2, age, wage ); while( strcmp(name, xxx ) ). } segmentation fault 4 (core dumped) segmentation fault (core dumped)
3 3 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) p1-p2 p1<>!= p2 Array as function argument decay Pass sub_array Arrays of pointers (5.6) Command line argument Pointer to arrays and two dimensional arrays Memory allocation Pointer to functions Pointer to structures Arrays of Pointers (5.6) Pointers are variables Can be arrayed like others (int, char, double) int * x[3] /* array of 3 integer pointers */ mnemonic x[i] is a integer pointer (int *) x[i] = &var *x[i] = 4; //set pointee **(x+i) =4; 6
4 4 Precedence and Associativity p53 Operator Type Operator Associativity Primary Expression Operators () []. -> left-to-right mnemonic Unary Operators Binary Operators * & + -! ~ (typecast) sizeof * / % arithmetic + - arithmetic >> << bitwise < > <= >= relational ==!= relational & ^ bitwise bitwise bitwise && logical logical right-to-left left-to-right Ternary Operator?: right-to-left int * x[3] /* array of 3 integer pointers */ char * x[5] /* array of 5 char pointers */ Assignment Operators = += -= *= /= %= >>= <<= &= ^= = right-to-left Comma, /*??? */ left-to-right char (*x)[5] Arrays of Pointers (5.6) Common use: array of char pointers (strings) char * words[]={ apple, cherry, banana }; char words[4][5]={ apple, cherry, banana }; //another words is an array of pointers to char (char *) Each element of words ( words[0], words[1], words[2]) is a pointer to char words apple cherry banana
5 5 Another example, initialization char * message[10] = { one, two, three }; 9 Another example, initialization char * message[10] = { one, two, three }; char arr[] = four ; message [8] = arr;
6 6 Arrays of Pointers (5.6) Common use: array of char pointers (strings) char * msg[]={ one, two, three }; Each element of msg (msg[0])is a pointer to char. msg[1] msg +1 *(msg+1) A pointer to two, address of t &msg[1], address of first pointer A pointer to two, address of t printf( s, *(msg+2) + 1 msg[1]) A two *(msg+2) + 1 & of h *( *(msg+2) + 1) h msg[2][1]? h Arrays of Pointers (5.6) Common use: array of char pointers (strings) char * msg[]={ one, two, three }; Each element of msg (e.g., msg[0])is a pointer to char. char **p; p = msg; // = & msg[0] *p? // msg[0] a pointer p+1? // & msg[1] *(p+1)? // *(msg+1) msg[1] p[1] **p ; // msg[0][0] o *(*(p+2)+1) //msg[2][1] h p[2][1]
7 7 Arrays of Pointers (5.6) Common use: array of char pointers (strings) char * msg[]={ one, two, three }; Each element of msg (e.g., msg[0])is a pointer to char. char **p; p = msg; printf("%s\n", *p ); // msg[0] one printf("%s\n",*(p+1) );// msg[1] two printf("%c\n", **p ); // msg[0][0] printf("%c\n", *(*(p+1)+2) ); //msg[1][2] o printf("%c\n", *(*(p+2)+1 )); //msg[2][1] h 13 printf("%c\n", *(*(p+2)+2) +1 ); Passing an array of pointers to function main(){ char *message[3] = { one, two, three }; printf( %s, message[1]); // two print_message(message, 3); } void print_message(char *p[], int n){ int count; for (count=0; count<n; count++) printf( %s, p[count]); } 14 // *(p+count) Need to provide!!!
8 8 Passing an array of pointers to function main(){ char *message[3] = { one, two, three }; printf( %s, message[1]); // two print_message(message, 3); } Decay? Address of pointer void print_message(char **p, int n){ int count; for (count=0; count<n; count++) printf( %s, *(p + count) ); } 15 // p[count] Need to provide!!! Advantage of Pointer Arrays (vs. 2D array) char *name[] = {"Illegal month", "Jan", "Feb", "Mar" Ragged array sizeof(name)? 8*4=32 Total memory space? char aname[][15]={"illegal month","jan", "Feb", "Mar" 16 sizeof (aname)? 15*4=60
9 9 char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; 17 Advantage of Pointer Arrays (vs. 2D array) int a[10][20]; int *b[10]; a: 200 int-sized locations have been set aside. b: only 10 pointers are allocated and not initialized; initialization must be done explicitly. Assuming each element of b points to an array of 20 elements, total size = 200 integers + 10 pointers. Advantage of b: 1. the rows of the array may be of different lengths (saving space). 2. Another advantage? Swap rows! 18
10 10 char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; How to swap? plants[0] = plants[1]??? strcpy(tmp,p[0]) strcpy(p[0],p[1]) strcpy(p[1],tmp) How to swap? 19 char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"} Efficient manipulation of strings char *lines[]={ dog, apple, zoo, program, merry }; char * tmp = lines[0]; /* dog vs. apple */ lines[0] = lines[1]; // two char pointers lines[1] = tmp; tmp = lines[2]; /* zoo vs. merry */ lines[2] = lines[4]; // two char * pointers lines[4] = tmp; Exchange pointers (addresses) Not real data Exchange two addresses, That s it!!
11 11 public static void main(string[] args) Command-Line Arguments (5.10) Up to now, we defines main as int main() Usually it is defined as int main(int argc, char *argv[]) argc is the number of arguments (including program name) argv is an array containing the arguments. argv[0] is a pointer to a string with the program name. So argc is at least 1. (Java?) Optional arguments: argv[1] ~~ argv[argc-1] 21 argv[argc] is a NULL pointer. Command line arguments indigo 421 % a.out hello, world argv[0]: a.out argv[1]: hello, argv[2]: world args argc =
12 12 Command-Line Arguments (cont.) main( int argc, char *argv[] ) { int i; printf( Number of arg=%d\n, argc ); for( i=0; i<argc; i++ ) printf( %s\n, argv[i] ); } *(argv+i) > a.out Number of arg=1 argv[0]: a.out 23 >a.out how are you Number of arg=4 argv[0]: a.out argv[1]: how argv[2]: are argv[3]: you >a.out how are you Number of arg=3 argv[0]: a.out argv[1]: how argv[2]: are you Array of points vs. pointers to whole Array char *arr[3]; /* array of 3 pointers */ arr h i \0 arr+1? char (*arr)[3]; /* pointer to a 3 char array */ arr h i \0 arr+1? 24
13 13 Summary decay char a [20] char * p char *a [20] char ** p p p+1 char a [ ][8]? char (*p)[8] p p+1 p
14 14 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) p1-p2 p1<>!= p2 Array as function argument decay Pass sub_array Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Memory allocation Pointer to functions Pointer to structures IO Previous lecture Done Dynamic memory allocation scenario / motivation 1 When we define an array, we allocate memory for it int arr[20]; sets aside space for 20 ints This space is allocated at compile-time (i.e. when the program is compiled) 28
15 15 Dynamic memory allocation scenario / motivation 1 What if we do not know how large our array should be? In other words, we need to be able to allocate memory at run-time (i.e. while the program is running) How? scanf( %d, &n); int my_array[n]; /* not allowed in ANSI-C */ 29 Fortunately, C supports dynamic storage allocation: the ability to allocate storage during program execution. Using dynamic storage allocation, we can design data structures that grow (and shrink) as needed. The <stdlib.h> header declares three memory allocation functions: malloc Allocates a block of memory but doesn t initialize it. calloc Allocates a block of memory and clears it. realloc Resizes a previously allocated block of memory. These functions return a value of type void * (a generic pointer). 30
16 16 malloc() stdlib.h defines: void * malloc (int n); allocates memory at run-time returns a void pointer to the memory that has at least n bytes available (just allocated for you). Address of first byte Can be casted to any type 31 malloc() #include <stdlib.h> int main() { int *x; x = (int *) malloc(4); /*segmentation without this line */ } *x = 52; printf( %d\n, *x); segmentation fault (core dumped) 32
17 17 malloc() #include <stdlib.h> int main() { int *x; x = (int *) malloc(4); /*segmentation without this line */ *x = 52; printf( %d\n, *x); } Note: type conversion (cast) on result of malloc x = malloc(4); also works. Will convert 33 sizeof A better approach to ensure portability int *x; x = (int *) malloc( 4 ); x = (int *) malloc( sizeof(int) ); Note: a variable or lvalue argument can be surrounded by (), so: sizeof(x) works for both types and variables 34
18 18 NULL malloc() returns NULL when it cannot fulfill the request, i.e., memory allocation fails <stdio.h> defines macro NULL NULL == 0 as a pointer == points to nothing p = malloc(10000); if (p == NULL) { /* allocation failed; take appropriate action */ } else 35 if ( (p = malloc(10000)) == NULL) { /* allocation failed; take appropriate action */ }else. malloc() 7 #include <stdlib.h> -1 int main() { scanf( %d, &n); p +1 p +2 int * p = (int *) malloc(n * sizeof(int)); ( if (p == NULL) exit(0); 36 *p = 1; // p[0] = 1 *(p+1) = 2; // p[1]= 2 p[2] = 12; // *(p+2)= 12
19 19 calloc() vs. malloc() void *calloc(int n, int size); calloc(x, y) is pretty much the same as malloc(x * y) except malloc does not initialize memory calloc initializes memory content to 0 (zer0) free() malloc, calloc and the other memory allocation functions obtain memory blocks from a storage pool known as the heap. A block of memory that s no longer accessible to a program is said to be garbage. A program that leaves garbage behind has a memory leak. Some languages (Java!!!) provide a garbage collector that automatically locates and recycles garbage, but C doesn t. 38
20 20 Memory Leaks int *x; x = (int *) malloc( 20 ); x = (int *) malloc( 30 ); The first memory block (20 bytes) is lost for ever. MAY cause problems (exhaust memory). 39 free() Instead, each C program is responsible for recycling its own garbage by calling the free function to release unneeded memory. void free(void *ptr); frees memory we previously allocated, tells the system we no longer need this memory and that it can be reused address in ptr must have been returned from either malloc, calloc or realloc. 40 p = malloc( ); free(p);
21 21 realloc() resize a dynamically allocated array. char *ptr; ptr = malloc(20); ptr = realloc(ptr,50); void *realloc(void *ptr, int size); ptr must point to a memory block obtained by a previous call of malloc, calloc, or realloc. size represents the new size of the block, which may be larger or smaller than the original size. realloc(null, n) behaves like malloc(n). realloc (ptr, 0) behaves like free(prt), as it frees the memory block. 41 Better to check the results! #include<stdio.h> #include<stdlib.h> main() { int *a, i, n; printf( Input an array size ); scanf( %d, &n); if ((a = (int*)calloc(n, sizeof(int)) == NULL) exit(0); /* else, a already got the address from calloc */ a[0] = 5; *(a+1) = 30; for(i=2; i<n; i++) scanf( %d, &a[i]); // scanf( %d, a+i); printf( the first element is %d\n, a[0]); free(a); } 42
22 22 More on memory allocation We know the syntax But when to use it????? When need to allocate at run time, of course What else? Another feature of malloc -- request for heap space! 43 Whenever you need to access its pointee Ask yourself: Have you done one of the following 1. ptr = &var. /* direct */ var must not arr[20]; ptr=arr;variable 2. ptr = ptr2 /* indirect */ 3. ptr = (..)malloc(...) You do need to do one of above for: *ptr = var; var = *prt; ptr[2] = var scanf( %s, ptr) strcpy(ptr, hello ) strcat(ptr, hello ) fgets(ptr,.) 44
23 23 When to use malloc? When you need to allocate memory in run time, of course When you need memory space throughout the program running 1. ptr = &var. /* direct */ if var is a local variable in function 2. ptr = ptr2 /* indirect */ if ptr2 points to a local variable 3. ptr = (..)malloc(...) correct choice! var is in stack. Not in heap ; What is wrong here??
24 24 Stack vs. heap Local (stack) memory, automatic Allocated on function call, and variables deallocated automatically when creating function exits Dynamic heap memory The heap is an area of memory available to allocate areas ("blocks") of memory for the program. What I need! Not deallocated when function exits! 47 Request a heap memory: malloc/calloc in C, new in Java free() to deallocated in C, garbage collection in Java Stack vs. heap Local (stack) memory, automatic Allocated on function call, and deallocated automatically when function exits Dynamic heap memory The heap is an area of memory available to allocate areas ("blocks") of memory for the program. Not deallocated when creating function exits Request a heap memory: malloc / calloc / realloc in C new in C++ and Java o Student s = new Student(); What I need! 48 Deallocate from heap memory: free() in C, delete in C++ garbage collection in Java
25 25 (stack) (stack) (stack) ; i is in stack -- deallocated when function exits!!!
26 26 solution ; 51 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) p1-p2 p1<>!= p2 Array as function argument decay Pass sub_array Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Memory allocation Pointer to functions Pointer to structures IO reviewed Done
Quick review pointer basics (KR ch )
1 Plan for today Quick review pointer basics (KR ch5.1 5.5) Related questions in midterm Continue on pointers (KR 5.6 -- ) Array of pointers Command line arguments Dynamic memory allocation (malloc) 1
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationArrays and Pointers (part 2) Be extra careful with pointers!
Arrays and Pointers (part 2) EECS 2031 22 October 2017 1 Be extra careful with pointers! Common errors: l Overruns and underruns Occurs when you reference a memory beyond what you allocated. l Uninitialized
More informationArrays and Pointers (part 2) Be extra careful with pointers!
Arrays and Pointers (part 2) CSE 2031 Fall 2011 23 October 2011 1 Be extra careful with pointers! Common errors: Overruns and underruns Occurs when you reference a memory beyond what you allocated. Uninitialized
More informationLAB 6 (2017 June 22/27) Array of pointers. Dynamic memory allocation.
LAB 6 (2017 June 22/27) Array of pointers. Dynamic memory allocation. Due: June 30 (Fri) 11:59 pm Part I Array of pointers vs. 2D arrays. Command line arguments. 1. Problem A Motivation In class lots people
More informationPointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017
Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();
More informationIn Java we have the keyword null, which is the value of an uninitialized reference type
+ More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are
More informationC Structures & Dynamic Memory Management
C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail
More informationOther C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.
1 The previous lecture Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations Pointer basics 1 Common library functions [Appendix of K+R]
More informationDynamic memory allocation
Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes
More informationIntroduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved
Introduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved Overview (King Ch. 13, 22, 16-17) Strings (Ch. 13) Input/Output (Ch. 22) Structures (Ch. 16) Dynamic memory
More informationMemory (Stack and Heap)
Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03
More informationC: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36
Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example
More informationCS 11 C track: lecture 5
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 (from last week) Address: location where data stored
More informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationch = argv[i][++j]; /* why does ++j but j++ does not? */
CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and
More informationC: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to
More informationMultidimension array, array of strings
1 Multidimension array, array of strings char messages[3][7] ={ Hello, Hi, There ; Array of strings 0 1 2 0 1 2 3 4 5 6 H e l l o \0 H i \0 T h e r e \0 Each row (e.g., message[0]) is a char array (string)
More informationProgramming. Pointers, Multi-dimensional Arrays and Memory Management
Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship
More informationFrom Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides
From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor
More informationContent. In this chapter, you will learn:
ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];
More informationOutline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C
Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationHigh Performance Programming Programming in C part 1
High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the
More informationArray Initialization
Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]
More informationAnnouncements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1
Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic
More informationDynamic Data Structures. CSCI 112: Programming in C
Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable
More informationMemory Allocation in C
Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called
More informationDynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan
More informationArrays and Memory Management
Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationCSC 1600 Memory Layout for Unix Processes"
CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant
More informationCSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs
Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who
More informationo Code, executable, and process o Main memory vs. virtual memory
Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,
More informationComputer Programming Unit 3
POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very
More informationFirst of all, it is a variable, just like other variables you studied
Pointers: Basics 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 address (rather than the value)
More informationIntroduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities
More informationC BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.
C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,
More informationAPS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size
APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =
More informationntroduction to C CS 2022: ntroduction to C nstructor: Hussam Abu-Libdeh (based on slides by Saikat Guha) Fall 2011, Lecture 1 ntroduction to C CS 2022, Fall 2011, Lecture 1 History of C Writing code in
More informationDynamic Memory Allocation
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management
More informationArrays and Pointers in C. Alan L. Cox
Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including
More informationMemory Management. CS449 Fall 2017
Memory Management CS449 Fall 2017 Life9mes Life9me: 9me from which a par9cular memory loca9on is allocated un9l it is deallocated Three types of life9mes Automa9c (within a scope) Sta9c (dura9on of program)
More informationLecture 14. Dynamic Memory Allocation
Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 14-1 Lecture 14. Dynamic Memory Allocation The number of variables and their sizes are determined at compile-time before a program runs /*
More informationMemory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science
Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly
More informationCS 222: Pointers and Manual Memory Management
CS 222: Pointers and Manual Memory Management Chris Kauffman Week 4-1 Logistics Reading Ch 8 (pointers) Review 6-7 as well Exam 1 Back Today Get it in class or during office hours later HW 3 due tonight
More informationCS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017
CS 137 Part 5 Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors October 25th, 2017 Exam Wrapper Silently answer the following questions on paper (for yourself) Do you think that the problems on
More informationCE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location
More informationDynamic Allocation in C
Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,
More informationVariation of Pointers
Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationPOINTER AND ARRAY SUNU WIBIRAMA
POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program
More informationMIDTERM TEST EESC 2031 Software Tools June 13, Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes
MIDTERM TEST EESC 2031 Software Tools June 13, 2017 Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes This is a closed-book test. No books and notes are allowed. Extra space for
More informationDynamic Allocation of Memory
Dynamic Allocation of Memory Lecture 5 Section 9.8 Robb T. Koether Hampden-Sydney College Wed, Jan 24, 2018 Robb T. Koether (Hampden-Sydney College) Dynamic Allocation of Memory Wed, Jan 24, 2018 1 / 34
More informationUnderstanding Pointers
Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer
More informationMODULE 5: Pointers, Preprocessor Directives and Data Structures
MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two
More informationJagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming
Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationC: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/16 1-dimensional Arrays Arrays can be statically declared in C, such as: int A [100]; The space for this
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationLanguage comparison. C has pointers. Java has references. C++ has pointers and references
Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More informationProcesses. Johan Montelius KTH
Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other
More informationMemory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)
Memory Allocation Memory What is memory? Storage for variables, data, code etc. How is memory organized? Text (Code) Data (Constants) BSS (Global and static variables) Text Data BSS Heap Stack (Local variables)
More informationCS113: Lecture 5. Topics: Pointers. Pointers and Activation Records
CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",
More informationArrays, Pointers and Memory Management
Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by
More informationA process. the stack
A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes
More informationAgenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture
CS 61C: Great Ideas in Computer Architecture Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationC Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1
C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...
More informationMemory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24
Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program
More informationCS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic
More informationAbout Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More informationMemory Allocation. General Questions
General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to
More informationReview: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc
CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array
More informationIntroduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers
Introduction to C Geared toward programmers Ayush Dubey Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Cornell CS 4411, August 31, 2012 Administrative Information Outline
More informationINITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS
INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting
More informationIntroduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Sean Ogden Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Ayush Dubey Cornell CS 4411, August 30, 2013 Administrative Information
More informationIntroduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers
Introduction to C Geared toward programmers Zhiyuan Teo Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Cornell CS 4411, August 26, 2011 1 Administrative Information 2 Why C? 3
More informationCS24 Week 2 Lecture 1
CS24 Week 2 Lecture 1 Kyle Dewey Overview C Review Void pointers Allocation structs void* (Void Pointers) void* Like any other pointer, it refers to some memory address However, it has no associated type,
More informationMemory Management. CSC215 Lecture
Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time
More informationIntroduction to C Language (M3-R )
Introduction to C Language (M3-R4-01-18) 1. Each question below gives a multiple choice of answers. Choose the most appropriate one and enter in OMR answer sheet supplied with the question paper, following
More informationPointers. Introduction
Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.
More informationCS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic
More informationHigh-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet
High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy
More informationCS 61C: Great Ideas in Computer Architecture Introduction to C, Part III
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III Instructors: John Wawrzynek & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/fa15 1 Review, Last Lecture Pointers are
More informationChapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationCS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018
CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make
More informationPointers and File Handling
1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY
More informationNumber Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down
CS61C L3 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 More C intro, C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-25 Number Review Sign and magnitude
More informationDeclaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:
1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationAgenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011
CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture
More information