Systems Programming and Computer Architecture ( )
|
|
- Merry Sharyl Black
- 6 years ago
- Views:
Transcription
1 Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture ( ) Timothy Roscoe Herbstsemester 2016 AS 2016 Dynamic Memory Allocation 1
2 5: Dynamic memory allocation Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 2
3 Allocating memory so far counter is statically allocated allocated when program is loaded deallocated when program exits a, x, y are automatically allocated allocated when function is called deallocated when function returns // a global variable int counter = 0; int main(int argc, char *argv[]) { counter++; return 0; int foo(int a) { int x = a + 1; return x int main(int argc, char *argv[]) { int y = foo(10); return 0; AS 2016 Dynamic Memory Allocation 3
4 Often we want memory that Persists across multiple function calls, but not for the whole lifetime of the program. Is too big to fit on the stack. Is allocated and returned by a function as a result whose size is not known to the caller. // This is pseudo-c! char *ReadFile(char *filename) { int size = FileSize(filename); char *buffer = AllocateMemory(size); ReadFileIntoBuffer(filename, buffer); return buffer; AS 2016 Dynamic Memory Allocation 4
5 Dynamically allocated memory Program explicitly requests new block of memory Language runtime allocates it, perhaps using the OS Dynamically allocated memory persists until: code explicitly deallocates it [manual memory management], or garbage collector collects it [automatic memory management] C requires manual memory management Much more control Much more care needed AS 2016 Dynamic Memory Allocation 5
6 This is the heart of C! and much systems programming! Non-trivial C programs are all about: Allocating and managing memory explicitly Filling it with structured types Using pointers to build complex dynamic data structures AS 2016 Dynamic Memory Allocation 6
7 5.1: The C memory API Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 7
8 malloc() // declared in stdlib.h typedef unsigned long size_t; void *malloc(size_t sz); Allocates a block of memory of the given size returns a pointer to the first byte of that memory returns NULL if the memory cannot be allocated you should assume the memory initially contains garbage typically use sizeof() to calculate the size you need float *arr = (float *)malloc(10*sizeof(float)); if (arr == NULL) { return ERRCODE; arr[0] = 5.1; // etc. AS 2016 Dynamic Memory Allocation 8
9 calloc() // declared in stdlib.h void *calloc(size_t nm, size_t sz); Allocates a block of memory size (nm sz) Like malloc(), a pointer to the first byte of that memory returns NULL if the memory cannot be allocated zeroes the memory - unlike malloc() Slightly slower, but less error-prone, more readable float *arr = (float *)calloc(10, sizeof(float)); if (arr == NULL) { return ERRCODE; arr[0] = 5.1; // etc. AS 2016 Dynamic Memory Allocation 9
10 Deallocation // declared in stdlib.h void free(void *); Releases memory at the pointer Must point to the first byte of malloc ed memory After freeing, memory might be reallocated by some future malloc()/calloc() Good practice to NULL the pointer after freeing. float *arr = (float *)calloc(10, sizeof(float)); if (arr == NULL) { return ERRCODE; // Do something... free(arr); arr = NULL; AS 2016 Dynamic Memory Allocation 10
11 Reallocation // declared in stdlib.h void *realloc(void *ptr, size_t size); Allocations have a fixed size. realloc() changes the size of the block As with free(), must point to first byte of a malloc ed block Might (almost certainly will!) copy the data to a new location Always use the new address returned! Returns NULL if failed. float *arr; if (!(arr = (float *)malloc(10*sizeof(float)))) { return ERRCODE; //... do something... if (!(arr = (float *)realloc(arr, 20*sizeof(float)))) { return ERRCODE; AS 2016 Dynamic Memory Allocation 11
12 A bit more about size_t size_t: An unsigned integer of some size Return type of sizeof() Large enough to hold the size of the largest possible array in memory can be used to store a pointer ptrdiff_t: An unsigned integer of some size Result of subtracting two pointers Used for array loops, size calculations, etc. Ends up identical to size_t AS 2016 Dynamic Memory Allocation 12
13 A variety of size models ( AS 2016 Dynamic Memory Allocation 13
14 Summary /* This program simply reads integers into a dynamic array until eof. The array is expanded as needed */ #include <stdio.h> #include <stdlib.h> // Initial array size #define INIT_SIZE 8 int main(int argc, char *argv[]) { int num; // Num. of integers int *arr; // Array of ints. size_t sz; // Array size int m, in; // Index & input num // Allocate the initial space. sz = INIT_SIZE; arr = (int *)calloc(sz, sizeof(int)); if (arr == NULL) { fprintf(stderr, realloc failed.\n"); exit(1); // Read in the numbers. num = 0; while(scanf("%d", &in) == 1) { // See if there's room. if(num >= sz) { // There's not. Get more. sz *= 2; arr = (int *)realloc(arr, sz*sizeof(int)); if(arr == NULL) { fprintf(stderr, realloc failed.\n"); exit(1); // Store the number. arr[num++] = in; // Print out the numbers for(m = 0; m < num; ++m) { printf("%d\n", arr[m]); free(arr); // Always good to free return 0; calloc.c AS 2016 Dynamic Memory Allocation 14
15 5.2: Managing the heap Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 15
16 Where does all this memory come from? The heap (or free store ) Large pool of unused memory, used for dynamically allocated data structures malloc() allocates chunks of memory in the heap, free() returns them malloc() maintains bookkeeping data in the heap to track allocated blocks. Kernel virtual memory User stack shared libraries Run-time heap Read/write segment (.data,.bss) Read-only segment (.init,.text,.rodata) Unused 0xffffffffffffffff 0x AS 2016 Dynamic Memory Allocation 16
17 Memory corruption There are lots of ways to corrupt memory in C. #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { int a[2]; int *b = malloc(2*sizeof(int)), *c; a[2] = 5; // assign past the end of an array a[0] += 2; // assume malloc zeroes out memory c = b+3; // mess up your pointer arithmetic free(&(a[0])); // pass pointer to free() that wasn't malloc'ed free(b); free(b); // double-free the same block b[0] = 5; // use a free()'d pointer // any many more! return 0; Dynamic Memory Allocation memcorrupt.c 17
18 Memory leaks A memory leak happens when code fails to deallocate memory that will no longer be used. // assume we have functions FileLen, // ReadFileIntoBuffer, and NumWordsInString int NumWordsInFile(char *filename) { char *filebuf = (char *)malloc(filelen(filename)+1); if (filebuf == NULL) { return -1; ReadFileIntoBuffer(filename, filebuf); // Leak! we never free(filebuf); return NumWordsInString(filebuf); AS 2016 Dynamic Memory Allocation 18
19 Implications of a leak Program s memory footprint will keep growing. For short-lived programs, this might be OK For long-lived programs, this is usually bad: Might slow down over time due to VM thrashing Might use up all available memory and crash Might starve other programs of memory Myth: garbage-collected languages like Eiffel and C# can t have memory leaks But they are are much less likely. AS 2016 Dynamic Memory Allocation 19
20 5.3: Structures and unions Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 20
21 Structured data struct typename { type name; type name; type name; ; // New structured data type called "struct Point" struct Point { float x,y; ; struct Point origin = { 0.0, 0.0 ; struct: a C type that contains a set of fields a bit like a class, but no methods or constructors instances can be allocated on stack or heap AS 2016 Dynamic Memory Allocation 21
22 Using structs Use "." to refer to fields in a struct Use "->" to refer to fields through a pointer to a struct struct Point { float x, y; ; int main(int argc, char **argv) { struct Point p1 = {0.0, 0.0; // p1 on the stack struct Point *p1_ptr = &p1; p->x is nicer than (*p).x p1.x = 1.0; p1_ptr->y = 2.0; return 0; simplestruct.c AS 2016 Dynamic Memory Allocation 22
23 Copy by assignment You can assign the value of a struct from a struct of the same type; this copies the entire contents #include <stdio.h> struct Point { float x, y; ; int main(int argc, char **argv) { struct Point p1 = {0.0, 2.0; struct Point p2 = {4.0, 6.0; printf("p1: {%f,%f p2: {%f,%f\n", p1.x, p1.y, p2.x, p2.y); p2 = p1; printf("p1: {%f,%f p2: {%f,%f\n", p1.x, p1.y, p2.x, p2.y); return 0; structassign.c Dynamic Memory Allocation 23
24 structs as arguments #include <stdio.h> // Point is a (struct point_st) // PointPtr is a (struct point_st *) typedef struct point_st { int x, y; Point, *PointPtr; void DoubleXBroken(Point p) { p.x *= 2; void DoubleXWorks(PointPtr p) { p->x *= 2; int main(int argc, char *argv) { Point a = {1,1; structs are passed by value like everything in C entire structure is copied to pass by reference, pass a pointer to a struct DoubleXBroken(a); printf("(%d,%d)\n", a.x, a.y); DoubleXWorks(&a); printf("(%d,%d)\n", a.x, a.y); return 0; structarg.c 24
25 You can return structs // a complex number is a + bi typedef struct complex_st { double real; // real component double imag; // imaginary component Complex, *ComplexPtr; Complex AddComplex(Complex x, Complex y) { Complex retval; retval.real = x.real + y.real; retval.imag = x.imag + y.imag; return retval; Complex MultiplyComplex(Complex x, Complex y) { Complex retval; retval.real = (x.real * y.real) - (x.imag * y.imag); retval.imag = (x.imag * y.real) - (x.real * y.imag); return retval; AS 2016 Dynamic Memory Allocation 25 complexstruct.c
26 Unions Like a struct, but holds only one of a set of alternative values: union u { int ival; float fval; char *sval; my_uval; Accessed like a struct No checking on which value is correct! AS 2016 Dynamic Memory Allocation 26
27 Summary Structured data: C structs Assigning structs Passing structs as arguments Returning structs Unions AS 2016 Dynamic Memory Allocation 27
28 5.4: Type definitions Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 28
29 typedef Introduces a new type definition New name for a type Examples: typedef unsigned uint32_t; uint32_t ui; typedef int **myptr; int *p; myptr mp = &p; typedef struct skbuf skbuf_t; skbuf_t *sptr; AS 2016 Dynamic Memory Allocation 29
30 Avoiding Complex Declarations Use typedef to build up the declaration Instead of int (*(*x[3])())[5] : typedef int fiveints[5]; typedef fiveints* p5i; typedef p5i (*f_of_p5is)(); f_of_p5is x[3]; x is an array of 3 elements, each of which is a pointer to a function returning an array of 5 ints AS 2016 Dynamic Memory Allocation 30
31 Struct tags and typedefs Structure tag struct list_el { unsigned long val; struct list_el *next; ; struct list_el my_list; Need the struct keyword to refer to a tag Also applies to unions AS 2016 Dynamic Memory Allocation 31
32 Struct tags and typedefs You can: Or even: typedef struct list_el el_t; typedef struct list_el { unsigned long val; struct list_el *next; el_t; Or even: struct list_el my_list; el_t my_other_list; typedef struct list_el { unsigned long val; struct list_el *next; list_el; struct list_el my_list; list_el my_other_list; Confusing. Better to stay with always using tags. AS 2016 Dynamic Memory Allocation 32
33 C namespaces 1. Label names (see goto ) 2. Tags one namespace for all struct, union, enum s 3. Member names One namespace for each struct, union, enum 4. Everything else (mostly) Including typedef AS 2016 Dynamic Memory Allocation 33
34 Summary Type definitions Structure and union tags C Namespaces AS 2016 Dynamic Memory Allocation 34
35 5.5: Dynamic data structures Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 35
36 Example: a singly-linked list Each node in the list contains: Some element as its payload A pointer to the next node in the linked list Last node in the list contains NULL instead of the next pointer. element Z element X head element Y AS 2016 Dynamic Memory Allocation 36
37 Linked list node Represent each node as a struct Assume for now each element is an int #include <stdio.h> typedef struct node_st { int element; struct node_st *next; Node; n1 element 1 next int main(int argc, char **argv) { Node n1, n2; element n2 n1.element = 1; n1.next = &n2; n2.element = 2; n2.next = NULL; return 0; manual_list.c next 2 NULL AS
38 Push() #include <stdio.h> #include <stdlib.h> #include <assert.h> (main) list typedef struct node_st { int element; struct node_st *next; Node; Node *Push(Node *head, int e) { Node *n = (Node *) malloc(sizeof(node)); assert(n!= NULL); // crashes if false n->element = e; n->next = head; (Push) head (Push) e (Push) n NULL 1 return n; int main(int argc, char **argv) { Node *list = NULL; element next 1 NULL list = Push(list, 1); list = Push(list, 2); return 0; push_list.c 38
39 Push() #include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct node_st { int element; struct node_st *next; Node; (main) list (Push) head Node *Push(Node *head, int e) { Node *n = (Node *) malloc(sizeof(node)); assert(n!= NULL); // crashes if false n->element = e; n->next = head; (Push) e (Push) n 2 return n; int main(int argc, char **argv) { Node *list = NULL; element next 1 NULL list = Push(list, 1); list = Push(list, 2); element next return 0; push_list.c 2 39
40 Push() #include <stdio.h> #include <stdlib.h> #include <assert.h> (main) list typedef struct node_st { int element; struct node_st *next; Node; Node *Push(Node *head, int e) { Node *n = (Node *) malloc(sizeof(node)); assert(n!= NULL); // crashes if false n->element = e; n->next = head; return n; int main(int argc, char **argv) { Node *list = NULL; element next 1 NULL list = Push(list, 1); list = Push(list, 2); element next return 0; push_list.c 2 40
41 Push() #include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct node_st { int element; struct node_st *next; Node; Node *Push(Node *head, int e) { Node *n = (Node *) malloc(sizeof(node)); a (benign) leak! Try running with valgrind: $ gcc o push_list g Wall push_list.c $ valgrind leak-check=full./push_list assert(n!= NULL); // crashes if false n->element = e; n->next = head; return n; int main(int argc, char **argv) { Node *list = NULL; element next 1 NULL list = Push(list, 1); list = Push(list, 2); element next return 0; push_list.c 2 41
42 5.6: Generic data structures Computer Architecture and Systems Programming , Herbstsemester 2016 Timothy Roscoe AS 2016 Dynamic Memory Allocation 42
43 A generic linked list We've seen a linked list of ints What if we want to let the client choose the element type? Idea: push a generic pointer (void *) instead. typedef struct node_st { void *element; struct node_st *next; Node; element Node *Push(Node *head, void *e) { Node *n = (Node *) malloc(sizeof(node)); next assert(n!= NULL); // crashes if false n->element = e; n->next = head; element return n; next NULL 43
44 Using a generic linked list To use it, clients need to use type casting Convert data type to a (void *) before pushing Convert from a (void *) back when accessing typedef struct node_st { void *element; struct node_st *next; Node; int main(int argc, char **argv) { char *hello = "Hi there!"; char *goodbye = "Bye bye."; Node *list = NULL; list = Push(list, (void *) hello); list = Push(list, (void *) goodbye); printf("payload is: '%s'\n", (char *) list->next->element); return 0; AS manual_list_void.c
45 Result (main) list (main) goodbye (main) hello element next B y e b y e. \0 element next NULL H i t h e r e! \0 AS 2016 Dynamic Memory Allocation 45
CSE 333 Lecture 4 - malloc, free, struct, typedef
CSE 333 Lecture 4 - malloc, free, struct, typedef Administrivia HW1 is due on Friday, January 25th, 11:15am - see course overview web page for the late policy Be sure to check out the course discussion
More informationCSE 333. Lecture 4 - malloc, free, struct, typedef. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 4 - malloc, free, struct, typedef Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia 1 New exercise out today, due Friday morning
More informationThe Heap and Structs. CSE 333 Spring Instructor: Justin Hsia
The Heap and Structs CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang
More informationCSE 333 Lecture 6 - data structures
CSE 333 Lecture 6 - data structures Steve Gribble Department of Computer Science & Engineering University of Washington Today s topics: - implementing data structures in C - multi-file C programs - brief
More informationCSE 333 Lecture 5 - data structures & modules
CSE 333 Lecture 5 - data structures & modules Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia HW1 out now, due in 2 weeks minus ε. Start early and make steady
More informationCSE 333 Lecture 6 - data structures
CSE 333 Lecture 6 - data structures Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Exercises: - ex5 is out: clean up the code from section yesterday, split
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 informationExercise Session 3 Systems Programming and Computer Architecture
Systems Group Department of Computer Science ETH Zürich Exercise Session 3 Systems Programming and Computer Architecture Herbstsemester 2016 Agenda Review of Exercise 2 More on C-Programming Outlook to
More informationSystems Programming and Computer Architecture ( )
Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 1 4: Pointers Computer Architecture and Systems Programming
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 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 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 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 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 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 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 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 informationData Structures and Modules
Data Structures and Modules CSE 333 Autumn 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia
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 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 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 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 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 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 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 informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
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 informationDynamic memory allocation (malloc)
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
More informationDeep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems
Deep C Multifile projects Getting it running Data types Typecasting Memory management Pointers Fabián E. Bustamante, Fall 2004 Multifile Projects Give your project a structure Modularized design Reuse
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 informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationCS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space Dynamic Memory Allocation All variables, arrays, structures and unions that we worked with so far are statically allocated,
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 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 informationHeap Arrays. Steven R. Bagley
Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,
More informationunsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables
Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char
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 informationTutorial 1: Introduction to C Computer Architecture and Systems Programming ( )
Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough
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 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 informationWeek 9 Part 1. Kyle Dewey. Tuesday, August 28, 12
Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly
More informationClass Information ANNOUCEMENTS
Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to
More informationPointers, Arrays, Memory: AKA the cause of those Segfaults
Computer Science 61C Spring 2018 Wawrzynek and Weaver Pointers, Arrays, Memory: AKA the cause of those F@#)(#@*( Segfaults 1 Agenda Computer Science 61C Spring 2018 Pointers Arrays in C Memory Allocation
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 informationDynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Dynamic Memory Management Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Dynamic Memory Allocation Dynamic memory allocation is used to
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 informationC for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.
C for Java Programmers 1 Last Week Very short history of C Overview of the differences between C and Java The C language (keywords, types, functies, etc.) Compiling (preprocessor, compiler, linker) C for
More informationMPATE-GE 2618: C Programming for Music Technology. Unit 5.1
MPATE-GE 2618: C Programming for Music Technology Unit 5.1 Review: automatic vs. static variables Variables declared and passed to functions are automatic variables. As soon as you leave the function,
More informationEL2310 Scientific Programming
Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory
More informationCS 110 Computer Architecture. Lecture 4: Introduction to C, Part III. Instructor: Sören Schwertfeger.
CS 110 Computer Architecture Lecture 4: Introduction to C, Part III Instructor: Sören Schwertfeger http://shtech.org/courses/ca/ School of Information Science and Technology SIST ShanghaiTech University
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 informationCMPSC 311- Introduction to Systems Programming Module: Types, Structs and Unions
CMPSC 311- Introduction to Systems Programming Module: Types, Structs and Unions Professor Patrick McDaniel Fall 2014 Types A data type is an abstraction that allows a programmer to treat different memory
More informationBase Component. Chapter 1. *Memory Management. Memory management Errors Exception Handling Messages Debug code Options Basic data types Multithreading
Chapter 1. Base Component Component:, *Mathematics, *Error Handling, *Debugging The Base Component (BASE), in the base directory, contains the code for low-level common functionality that is used by all
More informationCMPSC 311- Introduction to Systems Programming Module: Types, Structs and Unions
CMPSC 311- Introduction to Systems Programming Module: Types, Structs and Unions Professor Patrick McDaniel Fall 2015 Types A data type is an abstraction that allows a programmer to treat different memory
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 informationPrograms in memory. The layout of memory is roughly:
Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program
More informationCMPS 105 Systems Programming. Prof. Darrell Long E2.371
+ CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =
More informationECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee
ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia
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 informationRicardo Rocha. Department of Computer Science Faculty of Sciences University of Porto
Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()
More informationPointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator
Introduction To Pointers Pointers and Arrays For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 A pointer in C++ holds the value of a memory address A pointer's
More informationCS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.
CS 33 Intro to Storage Allocation CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. A Queue head typedef struct list_element { int value; struct list_element
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 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 informationMemory Organization. The machine code and data associated with it are in the code segment
Memory Management Memory Organization During run time, variables can be stored in one of three pools : 1. Stack 2. Global area (Static heap) 3. Dynamic heap The machine code and data associated with it
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 informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
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 informationCOSC345 Software Engineering. The Heap And Dynamic Memory Allocation
COSC345 Software Engineering The Heap And Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines Virtual memory Swapping
More informationQuick 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 information(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University
(13-2) Dynamic Data Structures I H&K Chapter 13 Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University Dynamic Data Structures (1) Structures that expand and contract
More informationCSE 333 Lecture 2 Memory
CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking
More informationReminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations
Reminder of midterm 1 Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations A New Example to see effect of E++ (better than the one in previous lecture) Purpose of showing
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 informationCS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models
CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models Instructors: Nicholas Weaver & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Pointer Ninjitsu: Pointers
More informationSection 2: Processes
September 7, 2016 Contents 1 Warmup 2 1.1 Hello World............................................ 2 2 Vocabulary 2 3 Problems 3 3.1 Forks................................................ 3 3.2 Stack Allocation.........................................
More informationIntroduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th
Introduction to Computer Systems 15 213/18 243, fall 2009 16 th Lecture, Oct. 22 th Instructors: Gregory Kesden and Markus Püschel Today Dynamic memory allocation Process Memory Image %esp kernel virtual
More information14. Memory API. Operating System: Three Easy Pieces
14. Memory API Oerating System: Three Easy Pieces 1 Memory API: malloc() #include void* malloc(size_t size) Allocate a memory region on the hea. w Argument size_t size : size of the memory block(in
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 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 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 informationThe output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {
Memory A bit is a binary digit, either 0 or 1. A byte is eight bits, and can thus represent 256 unique values, such as 00000000 and 10010110. Computer scientists often think in terms of hexadecimal, rather
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 information19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)
Lecture 29 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 29: Linked Lists 19-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vlado Keselj Previous
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 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 informationDynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1
Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses
More informationDynamic Memory Allocation
Dynamic Memory Allocation Computer Systems Organization (Spring 2017) CSCI-UA 201, Section 3 Instructor: Joanna Klukowska Slides adapted from Randal E. Bryant and David R. O Hallaron (CMU) Mohamed Zahran
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 informationCOSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation
COSC345 2013 Software Engineering Lectures 14 and 15: The Heap and Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines
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 informationDynamic Data Structures (II)
Lecture 23 Dynamic Data Structures (II) CptS 121 Summer 2016 Armen Abnousi Data Structure Data structures are different ways of organizing data in computer We design new data structures to make the programs
More informationMemory Management I. two kinds of memory: stack and heap
Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation)
More informationECE 551D Spring 2018 Midterm Exam
Name: SOLUTIONS ECE 551D Spring 2018 Midterm Exam NetID: There are 6 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam
More informationCS C Primer. Tyler Szepesi. January 16, 2013
January 16, 2013 Topics 1 Why C? 2 Data Types 3 Memory 4 Files 5 Endianness 6 Resources Why C? C is exteremely flexible and gives control to the programmer Allows users to break rigid rules, which are
More informationLimitations of the stack
The heap hic 1 Limitations of the stack int *table_of(int num, int len) { int table[len+1]; for (int i=0; i
More informationActually, C provides another type of variable which allows us to do just that. These are called dynamic variables.
When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called
More informationA brief introduction to C programming for Java programmers
A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically
More informationCS61C Midterm Review on C & Memory Management
CS61C Midterm Review on C & Memory Management Fall 2006 Aaron Staley Some material taken from slides by: Michael Le Navtej Sadhal Overview C Array and Pointer Goodness! Memory Management The Three Three
More information