LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically.

Size: px
Start display at page:

Download "LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically."

Transcription

1 C PROGRAMMING LANGUAGE. MEMORY MANAGEMENT. APPLICATION TO ARRAYS. CAAM 519, CHAPTER 7 This chapter aims to describe how a programmer manages the allocation of memory associated to the various variables used by a C program. This chapter also presents how to allocate dynamic memory when working with (multidimensional) arrays. 1. Memory management The variables involved in a C program can be stored either statically or dynamically Static memory. Variables and functions can be saved with static memory so that their lifespan is the same as the lifetime of the program. The memory size required to store a static variable or function is determined and allocated when the program starts. It can not be changed later in the execution of the program. Static memory allocation is mainly used when a programmer wants to work with the same variable on multiple functions or source files. Global variables, variables defined outside functions, are automatically stored as static variable. Developers can also tell the program to store a variable or a function with static memory by using the attribute static or extern during its declaration. We remind that a variable defined with the static attribute in a function keeps its value between the invocations of the function. When a global variable or a function is declared as static, it restricts its scope to the source file it is declared in Dynamic memory. Variable can also be saved dynamically meaning their lifespan is smaller than the lifetime of the executable. Such memory allocation is either done automatically or manually Automatic memory allocation on the Stack. When declaring a local variable without the attribute static or extern, the variable is automatically stored with dynamic memory on a memory region of the RAM called Stack. The memory used to store the variable is free as soon as the function where it is defined ends. Memory allocated in the Stack is done in a LIFO (Last In First Out) order. Although access to variables stored in the Stack is very fast, this memory region does not allow to store large data as its size is around 10 Mo. Moreover, the programmer can not manage memory allocated in the Stack. It means that a pointers or an array defined in a function and stored on the Stack can not be used outside the function. To face these issues, the C language allows the programmer to do dynamical memory allocation manually on a region called the Heap. This feature is described in the following section Dynamical memory allocation on the Heap. Programmers can manage manually the dynamical memory allocation of variables. The memory is then allocated on a region of the RAM called Heap. Unlike the Stack, the memory size used by the HEAP is only limited by the size of virtual memory (RAM). In addition, the size of a memory s block associated to a variable (pointer) can be 1

2 2 reallocated if a larger or smaller size is needed. However, access to data is a little slower as variable can be stored anywhere in the virtual memory of the computer. In C, doing a dynamical memory allocation of a variable manually is referred as dynamical memory allocation. This feature can be used in many situations such as (non exhaustive list): Memory to allocate is too large to be stored on the Stack. Return pointer with functions. Need to change the size of the block of memory associated to a pointer. The following section shows how to manage dynamical memory allocation of variables on the Heap Manage manual dynamic allocation on the heap. This feature of C mainly involves four functions respectively named malloc, calloc, realloc and free. These functions are part of the library stdlib.h. The first two functions, malloc and calloc, allow to allocate the required memory associated to a pointer on the Heap. It is then possible to reallocate (change the size) an allocated pointer with realloc and to deallocate the memory associated to a pointer with the function free malloc. Allocate a block of memory and return a pointer that contains the memory address of the first element allocated. The general structure of a call of malloc is the following: type_ pointer * pointer_ name ; pointer_ name = ( type_ pointer *) malloc ( nb_ bytes ); where pointer name is the name of the pointer, type pointer is the type of elements pointed to by the pointer and nb bytes is the number of bytes that are allocated. This number of bytes should be equal to the number of elements stored times the size in bytes of an element. The initial data contains by the pointer can be anything as malloc does not initialize the bytes allocated calloc. Allocate a block of memory and return a pointer that contains the memory address of the first element allocated. Unlike malloc, the function calloc initializes the allocated memory to zero (in terms of bytes). The arguments of this function are the number of elements to allocate and the number of bytes used to store one element. It is called as follows. type_ pointer * ptr ; ptr = ( type_ pointer *) calloc ( nb_ele, bytes_ per_ ele ); The number bytes per ele should be the number of bytes of type pointer. It can be evaluated with sizeof(type pointer) realloc. Resize the length of a block of memory pointed to by a pointer previously allocated with the functions malloc or calloc. The function takes a pointer and a number of bytes as argument. Its structure is the following. type_ pointer * ptr ; ptr = ( type_ pointer *) malloc ( nb_ bytes ); ptr = ( type_ pointer *) realloc ( ptr, new_ nb_ bytes );

3 C PROGRAMMING LANGUAGE: MEMORY MANAGEMENT AND ARRAY free. Deallocate (free) a block of memory that was previously allocated by a call to malloc, calloc or realloc. You can use this function as follows: type_ pointer * ptr ; ptr = ( type_ pointer *) malloc ( nb_ bytes ); free ( ptr ); It is important to always deallocate pointers that are not used anymore in your code. Failing to do so may lead your program to generate memory leak or use too much memory. Remark: When using dynamical memory allocation, a programmer should be cautious with the following four issues. Uninitialized memory. It can happens when using a pointer allocated with the function malloc. Memory overwrite. C does not forbid to access data that are written in the following bytes associated to a pointer. For instance in the following example, we are going to overwritte on four bytes that could be used by other variables or programs. int * ptr ; ptr = ( int *) malloc (2* sizeof ( int )); ptr [3]=4; // overwrite Memory overread. This issue has similar consequence as uninitialized memory: the data read by the program are not relevant as they are not part of a block of memory the programmer allocated to a pointer. Here is an example of overread issue. int * ptr ; ptr = ( int *) malloc (2* sizeof ( int )); int a= ptr [3]; // overread Memory leak. This issue concerns block of memory, previously allocated to a pointer, that are made inaccessible before being free. For instance, it can happens when a programmer redefines the address of a pointer before freeing the memory associated to the pointer. Same problem can arise when declaring a pointer with dynamic memory allocation in a function without returning the pointer or freeing the pointer in the function. It is possible to fix the memory leak of a program using the software valgrind. We will describe later in the course how to use valgrind and a C debugger called gdb. We refer to the example provided on CAAM519 course webpage for more information on how to use the above functions. The next section focuses on allocating array with dynamical memory. 2. Array and dynamic memory allocation 2.1. Storage of array in a C program. We remind that a one dimensional array can be defined by using a square bracket during its declaration as follows: int tab [ 4]; // Array of 4 integers while a multidimensional array is declared with multiple square brackets to respect the following structure. int tab [4][3]; // Matrix 4x3 of integers

4 4 The memory allocated to declare array is automatically done on the Stack. Meaning that the array, and the pointers associated to the memory address of the first element of the array, only lives in the function where it is declared/defined. Regarding multidimensional array, it is important to note that C uses a row major indexation (versus column major for Fortran). Moreover, all the values of the array s element are stored in a continuous large block of memory. It means that the first blocks of memory used to store the array contains information on the value of the elements of the first row of the array. Then the following blocks of memory contains information on the elements of the array s second row, and so on. Here is an example of code that show various way of accessing the value of an element of a two dimensional array. int M [4][3]; int i,j,k; for (i =0; i <4; i ++){ for (j =0; j <3; j ++){ k = 3*i+j; // Arrray notation M[i][j]=k; // Equivalent notation with pointers *(M[i]+j)=k; *(M [0]+ k )=4; M [0][ k]=k; (*M)[k]=k; *((* M)+k)=k; Note that it is also possible to define a multidimensional array as a one dimensional array of length equal to the product of the dimensions of the array. It terms of memory storage, the memory allocated to the array presents the same structure. However the access to the array s elements will differ Dynamical memory allocation of array. The previous declaration of arrays does not allow the programmer to manage the memory associated to this array. To face this, we can use dynamical memory allocation of pointers with the functions malloc and calloc. The allocated pointers can be used to represent arrays. In addition to be able to manage the pointer s lifetime, such declaration also allows to reallocate the size of the memory block associated to the pointer. The following sections show how a developer can use the functions malloc and calloc to declare pointer associated to a one and multidimensional array One dimensional array. Use of malloc to create a pointer of an array of a various length. int * M; int length =4; // Create pointer to an array of four integers M = ( int *) malloc ( length * sizeof ( int )); Similar declaration can be done with the function calloc.

5 C PROGRAMMING LANGUAGE: MEMORY MANAGEMENT AND ARRAY Multidimensional array. There is multiple ways of declaring multidimensional array with pointer that are allocated with a dynamic memory on the heap. In this section we focus on working with 2D arrays that have the following dimensions: int rows = 3; int columns = 4; The allocation of an array of dimension (rows, columns) can be done with the following methods. Use one pointer. The memory allocated has to be equal to the size of the array, i.e. the number of rows times the number of columns time the size in bytes of each element of the array. It can be done as follows. int *pt = ( int *) malloc ( rows * columns * sizeof ( int )); To access the element of the array, one needs to navigate with the address contains in the pointer as shown here: for ( int j =0; j< columns ; j ++){ // Set the value of the element ( i, j) *( pt + i* columns + j) = 1; // pt[i* columns + j] = 1; The memory can be free with the command free (pt ); Use a pointer to a pointer. The structure of such allocation is the following: int ** pt = ( int **) malloc ( rows * sizeof ( int *)); pt[i] = ( int *) malloc ( columns * sizeof ( int )); The first line allocates a pointer that contains address of other pointers that represent the rows of the array. In the loop for, a block of memory that fits the size of a column is allocated and its address is given to pt[i]. The element of the array can they be accessed as follows: for ( int j =0; j< columns ; j ++){ // Set the value of the element ( i, j) pt[i][j] = 1; // *(*( pt+i)+j) = 1; Note that to free the allocated memory, the following command has to be performed:

6 6 free (pt[i ]); // Free a block of a column size. free ( pt ); // Free the memory of the pointer to pointer. Use a pointer to a pointer with contiguous memory. int ** pt = ( int **) malloc ( rows * sizeof ( int *)); // Allocate a memory block that can contains the 2 D array pt [0] = ( int *) malloc ( rows * columns * sizeof ( int )); for ( int i =1; i< rows ; i ++){ // Set correct memory address for each rows pt[i] = pt [0] + columns *i; The element can be accessed the same way than the previous method. The advantage of this method is that the memory blocks that contains the information on the array s element are contiguous. The memory can be free as follows: free (pt [0]); free (pt ); In general, we will prefer the last method as it is the more efficient. Moreover, it allows to access the elements of the matrix in a standard way (i.e. using [i][j]). Note that each call of malloc or calloc requires a call to free to deallocate the memory blocks that were requested. Remark on 3D matrix. One can use dynamic memory on the heap to allocate 3D (or larger) matrix using the previous methods. Here is an example that consider the allocation of a 3D matrix of dimensions (dim1, dim2, dim3) using pointer of pointer with contiguous memory. int *** pt = ( int ***) malloc ( dim1 * sizeof ( int **)); pt [0] = ( int **) malloc ( dim1 * dim2 * sizeof ( int *)); // Allocate a memory block that can contains the 3 D array pt [0][0] = ( int * ) malloc ( dim1 * dim2 * dim3 * sizeof ( int )); // Set correct memory address for each rows ( first dimension ). for ( int i =0; i< dim1 ; i ++){ pt[i] = pt [0] + dim2 *i; // Set correct memory address for 2 nd dimension for ( int j =0; j< dim2 ;j ++){ pt[i][j]= pt [0][0] + dim2 * dim3 *i + dim3 *j; We refer to the class for more details on this example Function returning array. Declaring an array or a pointer in a function does not allow to use it as output when it is automatically allocated on the stack. Indeed the memory allocated on the stack by a function is free as soon as the function ends. To face this issue, it is possible to write functions that return arrays or pointer if one declares the arrays/pointers with the functions malloc

7 C PROGRAMMING LANGUAGE: MEMORY MANAGEMENT AND ARRAY. 7 or calloc. The memory allocated to the array is then stored on the heap and is only free when the programmer decides so by using the function free. int * create_ int_ array ( int lenght_ array ){ int * pt; pt = ( int *) calloc ( lenght_ array, sizeof ( int )); return pt; Remark: It is important to free such pointers if they are not used as output of the function. Indeed when allocating pointer with the function malloc or calloc in a function, it will be impossible to free the allocated memory if the pointers is not returned or free in the function. Failing to do so will result in a program with memory leak Function with multidimensional array as argument. To use a multidimensional array as a function argument, the programmer has to specified the dimensions of the array in the function s declaration (or at least all of the dimensions but the first one). Here is an example of a prototype of such a function: void function ( int tab [][3][4]); In addition, we note that it is not possible to determine the length/dimensions of the input array using only the array. Indeed an array is passed as a pointer that contains the address of the first byte where elements of the array are stored. The pointer does not contain any information about the length (or dimensions) of the array. As a consequence, the dimensions of an array should also be passed as argument to avoid overreading or overwriting issues. The above prototype would become: void function ( int tab [][3][4], int, int, int ); We remind that it is possible to determine the dimensions of an array in the function where it is declared using the function sizeof. For instance here is how to compute the first and second dimension of an array. int array [4][2][3]; int first_dim = sizeof ( tab )/ sizeof ( tab [0]); int second_dim = sizeof ( tab [0])/ sizeof ( tab [0][0]); The above code can not be used in a function with tab as argument because tab is now a pointer for the function sizeof. The results of the above lines will then vary between different machine/operating system. We refer to the example ex 14 func array pointer.c available on CAAM 519 s webpage, for more information Inconvenient and outlook. To construct matrix and access the elements of the matrix as introduced in this chapter, the programmer always needs to work with the memory address of the elements. It is not always very safe to do as a typo in a program can lead to various memory error (overread or overwrite). To limit such interactions, we can create structure that contains matrix, dimensions of matrix and function that work on the matrix (access to an element, scalar product, etc.). Such feature is introduced in the next chapter and presents one main advantage: once a matrix structure is properly set the programmer may avoid working with memory address or equivalent elsewhere in the program.

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In 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 information

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 1. Pointers As Kernighan and Ritchie state, a pointer is a variable that contains the address of a variable. They have been

More information

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Week 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 information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring 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 information

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

APS105. 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 information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic 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 information

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 This chapter focuses on introducing the notion of classes in the C++ programming language. We describe how to create class and use an object of a

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic 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 information

Scientific Programming in C IV. Pointers

Scientific Programming in C IV. Pointers Scientific Programming in C IV. Pointers Susi Lehtola 1 November 2012 Pointers The feature at the heart of C are pointers, which are simply pointers to memory addresses. Scientific Programming in C, fall

More information

Dynamic Memory Allocation

Dynamic 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 information

Dynamic Allocation in C

Dynamic 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 information

Memory Management. CSC215 Lecture

Memory 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 information

CS 11 C track: lecture 5

CS 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 information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: 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 information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

Dynamic memory allocation

Dynamic 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 information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. 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 information

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1 MPATE-GE 2618: C Programming for Music Technology Unit 4.1 Memory Memory in the computer can be thought of as a long string of consecutive bytes. Each byte has a corresponding address. When we declare

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 (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 information

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

advanced 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 information

Arrays, Pointers and Memory Management

Arrays, 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 information

Memory (Stack and Heap)

Memory (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 information

Dynamic Allocation in C

Dynamic Allocation in C Dynamic Allocation in C 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, as the program

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays 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 information

CS201- Introduction to Programming Current Quizzes

CS201- 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 information

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows: Pointers and Arrays Part II We will continue with our discussion on the relationship between pointers and arrays, and in particular, discuss how arrays with dynamical length can be created at run-time

More information

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

Dynamic Memory. R. Inkulu (Dynamic Memory) 1 / 19

Dynamic Memory. R. Inkulu  (Dynamic Memory) 1 / 19 Dynamic Memory R. Inkulu http://www.iitg.ac.in/rinkulu/ (Dynamic Memory) 1 / 19 Types of memory allocations auto local * allocated on stack and uninitialized by default * accessible in the function that

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays 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 information

Intermediate Programming, Spring 2017*

Intermediate 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 information

C Programming Basics II

C Programming Basics II C Programming Basics II Xianyi Zeng xzeng@utep.edu Department of Mathematical Sciences The University of Texas at El Paso. September 20, 2016. Pointers and Passing by Address Upon declaring a variable,

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

(1-2) Introduction to C Data Structures & Abstract Data Types. Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University

(1-2) Introduction to C Data Structures & Abstract Data Types. Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University (1-2) Introduction to C Data Structures & Abstract Data Types Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University What is a Data Structure? A software construct describing

More information

Cpt S 122 Data Structures. Data Structures

Cpt S 122 Data Structures. Data Structures Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation

More information

Memory Allocation in C

Memory 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 information

Types II. Hwansoo Han

Types II. Hwansoo Han Types II Hwansoo Han Arrays Most common and important composite data types Homogeneous elements, unlike records Fortran77 requires element type be scalar Elements can be any type (Fortran90, etc.) A mapping

More information

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009 Lecture 5: Multidimensional Arrays CS209 : Algorithms and Scientific Computing Wednesday, 11 February 2009 CS209 Lecture 5: Multidimensional Arrays 1/20 In today lecture... 1 Let s recall... 2 Multidimensional

More information

CS61, Fall 2012 Section 2 Notes

CS61, 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 information

Dynamic memory allocation (malloc)

Dynamic 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 information

Reminder 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 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 information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: 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 information

o Code, executable, and process o Main memory vs. virtual memory

o 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 information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

CS11001/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 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 information

Pointers, Dynamic Data, and Reference Types

Pointers, 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 information

CS 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 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 information

Lectures 13 & 14. memory management

Lectures 13 & 14. memory management Lectures 13 & 14 Linked lists and memory management Courtesy of Prof. Garcia (UCB) CS61C L05 Introduction to C (pt 3) (1) Review Pointers and arrays are virtually same C knows how to increment pointers

More information

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

Understanding Pointers

Understanding 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 information

Warmup January 9th, What is the value of the following C expression? 8*9 % 10/ 2

Warmup January 9th, What is the value of the following C expression? 8*9 % 10/ 2 Warmup January 9th, 2018 What is the value of the following C expression? 8*9 % 10/ 2 Warmup January 11th, 2018 What is the value of the following C expression? ( -42 3!= 3) && ( -3 < -2 < -1) Warmup January

More information

CSCI 171 Chapter Outlines

CSCI 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 information

Dynamic Memory: Alignment and Fragmentation

Dynamic Memory: Alignment and Fragmentation Dynamic Memory: Alignment and Fragmentation Learning Objectives Explain the purpose of dynamic memory Define the terms arena, heap Identify common errors involving dynamic memory Explain how dynamic memory

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING 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 information

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

EL2310 Scientific Programming

EL2310 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 information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012 Instructions: This is a closed book, closed note exam. Calculators are not permitted. If you have a question, raise your hand and I will come to you. Please work the exam in pencil and do not separate

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 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 information

Exam 3 Chapters 7 & 9

Exam 3 Chapters 7 & 9 Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False

More information

Advanced Programming & C++ Language

Advanced Programming & C++ Language Advanced Programming & C++ Language ~6~ Introduction to Memory Management Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan Stack & Heap 2 The memory a program uses is typically divided into four different

More information

Arrays and Memory Management

Arrays 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 information

Variation of Pointers

Variation 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 information

C programming Lecture 2. Marina Krstic Marinkovic School of Mathematics Trinity College Dublin

C programming Lecture 2. Marina Krstic Marinkovic School of Mathematics Trinity College Dublin C programming 5613 Lecture 2 Marina Krstic Marinkovic marina.marinkovic@cern.ch School of Mathematics Trinity College Dublin Marina Krstic Marinkovic 1 / 10 5613 - C programming Arrays Array: indexed sequence

More information

CSC 211 Intermediate Programming. Arrays & Pointers

CSC 211 Intermediate Programming. Arrays & Pointers CSC 211 Intermediate Programming Arrays & Pointers 1 Definition An array a consecutive group of memory locations that all have the same name and the same type. To create an array we use a declaration statement.

More information

DAY 3. CS3600, Northeastern University. Alan Mislove

DAY 3. CS3600, Northeastern University. Alan Mislove C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue Memory management 2 Memory management Two

More information

Kurt Schmidt. October 30, 2018

Kurt 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 information

Computer Programming Unit 3

Computer 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 information

CMSC 341 Lecture 2 Dynamic Memory and Pointers

CMSC 341 Lecture 2 Dynamic Memory and Pointers CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Memory Allocation. General Questions

Memory 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 information

Pointers. Héctor Menéndez 1. November 28, AIDA Research Group Computer Science Department Universidad Autónoma de Madrid.

Pointers. Héctor Menéndez 1. November 28, AIDA Research Group Computer Science Department Universidad Autónoma de Madrid. Pointers Héctor Menéndez 1 AIDA Research Group Computer Science Department Universidad Autónoma de Madrid November 28, 2013 1 based on the original slides of the subject Index 1 Dynamic Memory 2 Arrays

More information

Class Information ANNOUCEMENTS

Class 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 information

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation ... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015 ... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++

More information

TI2725-C, C programming lab, course

TI2725-C, C programming lab, course Valgrind tutorial Valgrind is a tool which can find memory leaks in your programs, such as buffer overflows and bad memory management. This document will show per example how Valgrind responds to buggy

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation Lecture 15 COP 3014 Fall 2017 November 6, 2017 Allocating memory There are two ways that memory gets allocated for data storage: 1. Compile Time (or static) Allocation Memory

More information

a data type is Types

a data type is Types Pointers Class 2 a data type is Types Types a data type is a set of values a set of operations defined on those values in C++ (and most languages) there are two flavors of types primitive or fundamental

More information

Quick review pointer basics (KR ch )

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 information

Interlude: Memory API

Interlude: Memory API 13 Interlude: Memory API In this interlude, we discuss the memory allocation interfaces in UNIX systems. The interfaces provided are quite simple, and hence the chapter is short and to the point 1. 13.1

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = 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 information

ECE 15B COMPUTER ORGANIZATION

ECE 15B COMPUTER ORGANIZATION ECE 15B COMPUTER ORGANIZATION Lecture 13 Strings, Lists & Stacks Announcements HW #3 Due next Friday, May 15 at 5:00 PM in HFH Project #2 Due May 29 at 5:00 PM Project #3 Assigned next Thursday, May 19

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018 Hacking in C Memory layout Radboud University, Nijmegen, The Netherlands Spring 2018 A short recap The & operator gives us the address of data Inverse of & is the * operator (dereferencing) 2 A short recap

More information

Lecture 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? 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 information

Dynamic 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 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 information

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

COMP26120: Linked List in C (2018/19) Lucas Cordeiro COMP26120: Linked List in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Linked List Lucas Cordeiro (Formal Methods Group) lucas.cordeiro@manchester.ac.uk Office: 2.28 Office hours: 10-11 Tuesday,

More information

Content. In this chapter, you will learn:

Content. 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 information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

University of California San Diego Department of Electrical and Computer Engineering. ECE 15 Final Exam

University of California San Diego Department of Electrical and Computer Engineering. ECE 15 Final Exam University of California San Diego Department of Electrical and Computer Engineering ECE 15 Final Exam Tuesday, March 21, 2017 3:00 p.m. 6:00 p.m. Room 109, Pepper Canyon Hall Name Class Account: ee15w

More information

Contents of Lecture 3

Contents of Lecture 3 Contents of Lecture 3 Repetition of matrices double a[3][4]; double* b; double** c; Terminology Linkage Types Conversions Jonas Skeppstedt (js@cs.lth.se) Lecture 3 2014 1 / 33 A global matrix: double a[3][4]

More information

dynamic memory allocation

dynamic memory allocation Dynamic memory allocation in C The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

Pointers (1A) Young Won Lim 11/1/17

Pointers (1A) Young Won Lim 11/1/17 Pointers (1A) Copyright (c) 2010-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

Lecture 14 Notes. Brent Edmunds

Lecture 14 Notes. Brent Edmunds Lecture 14 Notes Brent Edmunds October 5, 2012 Table of Contents 1 Sins of Coding 3 1.1 Accessing Undeclared Variables and Pointers...................... 3 1.2 Playing With What Isn t Yours..............................

More information

CS 230 Programming Languages

CS 230 Programming Languages CS 230 Programming Languages 11 / 20 / 2015 Instructor: Michael Eckmann Questions/comments? Chapter 6 Arrays Pointers Today s Topics We all know what arrays are. Design issues Legal types for subscripts

More information

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Pointers, 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 information

Heap Arrays. Steven R. Bagley

Heap 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 information

Lecture 7: Procedures and Program Execution Preview

Lecture 7: Procedures and Program Execution Preview Lecture 7: Procedures and Program Execution Preview CSE 30: Computer Organization and Systems Programming Winter 2010 Rajesh Gupta / Ryan Kastner Dept. of Computer Science and Engineering University of

More information