Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

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

Pointers, Arrays, and Strings. CS449 Spring 2016

Pointers. September 13, 2017 Hassan Khosravi / Geoffrey Tien 1

Computer Programming Unit 3

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

Class Information ANNOUCEMENTS

APSC 160 Review Part 2

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Dynamic Allocation in C

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

DAY 3. CS3600, Northeastern University. Alan Mislove

High Performance Programming Programming in C part 1

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CSC 1600 Memory Layout for Unix Processes"

Dynamic Allocation in C

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

CS 11 C track: lecture 5

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Memory Management. CSC215 Lecture

CS61, Fall 2012 Section 2 Notes

Procedural programming with C

ECE 551D Spring 2018 Midterm Exam

Lecture 8 Dynamic Memory Allocation

Memory (Stack and Heap)

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

Arrays and Strings. CS449 Fall 2017

ECE551 Midterm Version 2

ECE 551D Spring 2018 Midterm Exam

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Dynamic memory allocation

CSC 270 Survey of Programming Languages. What is a Pointer?

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

Limitations of the stack

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Memory Allocation. General Questions

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Dynamic memory allocation (malloc)

C PROGRAMMING Lecture 5. 1st semester

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

ECE551 Midterm Version 1

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

Memory Allocation in C

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

CS201- Introduction to Programming Current Quizzes

Contents of Lecture 3

The 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 {

CSC209H1S Day Midterm Solutions Winter 2010

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Create a Program in C (Last Class)

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

ECE551 Midterm Version 1

Memory Organization. The machine code and data associated with it are in the code segment

Fall 2018 Discussion 2: September 3, 2018

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

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Data Structure Series

Object-Oriented Programming

Dynamic Memory Management

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Principles of C and Memory Management

Content. In this chapter, you will learn:

Pointers II. Class 31

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

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

Dynamic memory. EECS 211 Winter 2019

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Dynamic Allocation of Memory

Pointers. Memory. void foo() { }//return

Variation of Pointers

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Memory Management. CS449 Fall 2017

POINTER AND ARRAY SUNU WIBIRAMA

Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370

ECE 15B COMPUTER ORGANIZATION

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

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

Dynamic Memory Allocation

CSCI 171 Chapter Outlines

Pointers, Dynamic Data, and Reference Types

C Structures & Dynamic Memory Management

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

COMP 2355 Introduction to Systems Programming

Procedural Programming & Fundamentals of Programming

Intermediate Programming, Spring 2017*

Memory, Arrays & Pointers

C Programming Basics II

Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1

Section - Computer Science. int main() {! int a=10,b=20;! printf("a:%d B:%d\n",a,b);! a=(a+b)-(b=a);! printf("a:%d B:%d\n",a,b);!

C Tutorial Pointers, Dynamic Memory allocation, Makefile

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

int Return the number of characters in string s.

Dynamic Allocation of Memory

CS24 Week 2 Lecture 1

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Transcription:

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 of the other array elements (or whatever comes after, if it is meaningful) int A[5]; int* q = &A[0]; printf("q address: %p\n", q); A[0] = 2; A[1] = 4; printf("value of q: %d\n", *q); printf("value of q+1: %d\n", *(q + 1)); int x = 5; int* p = &x; printf("p address: %p\n", p); printf("value of p: %d\n", *p); printf("value of p+1: %d\n", *(p + 1)); September 18, 2017 Hassan Khosravi / Geoffrey Tien 2

Dynamic Memory Arrays declared as local variables must have a known size at compile time but sometimes we don't how much space we need until runtime Suppose we expect users to only need to store up to 1000 values, so we hard-code "1000" as an array size What if user needs more? What if user only needs 5? Change code and recompile Wastes memory If the value 1000 is hard-coded, this is hard to find and change especially if used in multiple locations If hardcoded as a symbolic constant, still cannot change without recompiling September 18, 2017 Hassan Khosravi / Geoffrey Tien 3

Memory management in C We have already seen how locally-declared variables are placed on the function call stack allocation and release are managed automatically The available stack space is extremely limited placing many large variables or data structures on the stack can lead to stack overflow Stack variables only exist as long as the function that declared them is running September 18, 2017 Hassan Khosravi / Geoffrey Tien 4

Dynamic memory allocation At run-time, we can request extra space on-the-fly, from the memory heap Request memory from the heap "allocation" Return allocated memory to the heap (when we no longer need it) "deallocation" Unlike stack memory, items allocated on the heap must be explicitly freed by the programmer September 18, 2017 Hassan Khosravi / Geoffrey Tien 5

Dynamic memory allocation Function malloc returns a pointer to a memory block of at least size bytes: ptr = (cast-type*) malloc(byte-size); Function free returns the memory block (previously allocated with malloc) and pointed to by ptr to the memory heap: free(ptr); The system knows how many bytes need to be freed, provided we supply the correct address ptr September 18, 2017 Hassan Khosravi / Geoffrey Tien 6

Heap example stack heap int main() { int a; int *p = (int*) malloc(sizeof(int)); *p = 10; } a p 4931 10 4931 If there is no free memory left on the heap, malloc will return a null pointer Note: malloc only allocates the space but does not initialize the contents. Use calloc to allocate and clear the space to binary zeros September 18, 2017 Hassan Khosravi / Geoffrey Tien 7

Allocating dynamic arrays Suppose we want to allocate space for exactly 10 integers in an array #include <stdio.h> #include <stdlib.h> int main() { int* i; i = (int*) malloc(10*sizeof(int)); if (i == NULL) { printf("error: can't get memory...\n"); exit(1); // terminate processing } } i[0] = 3; // equivalent: *(i+0) = 3; i[1] = 16; // *(i+1) = 16; printf("%d", *i);... September 18, 2017 Hassan Khosravi / Geoffrey Tien 8

Allocating dynamic arrays #include <stdio.h> #include <stdlib.h> From user input, variable array size int main() { int employees, index; double* wages; printf("number of employees? "); scanf("%d", &employees); wages = (double*) malloc(employees * sizeof(double)) if (!wages) { // equivalent: if (wages == NULL) printf("error: can't get memory...\n"); } } printf("everything is OK\n");... See dma_examples.c September 18, 2017 Hassan Khosravi / Geoffrey Tien 9

Dangling pointers When we are done with an allocated object, we free it so that the system can reclaim (and later reuse) the memory int main() { int* i = (int*) malloc(sizeof(int)); *i = 5; free(i); } printf("%d", *i); The space is marked as free, but the value remains until it is overwritten If the pointer continues to refer to the deallocated memory, it will behave unpredictably when dereferenced (and the memory is reallocated) a dangling pointer Leads to bugs that can be subtle and brutally difficult to find So, set the pointer to NULL after freeing i = NULL; September 18, 2017 Hassan Khosravi / Geoffrey Tien 10

Memory leaks If you lose access to allocated space (e.g. by reassigning a pointer), that space can no longer be referenced, or freed And remains marked as allocated for the lifetime of the program int* arr; int sz = 4; arr = (int*) malloc(sz*sizeof(int)); arr[2] = 5; arr = (int*) malloc(sz*sizeof(int)); arr[2] = 7; 4 stack heap 5 Lost access to this array! arr sz 7 See memory_leak.c September 18, 2017 Hassan Khosravi / Geoffrey Tien 11

Exercise What is printed to the screen? Also clearly identify memory leaks and dangling pointers int w; int z; int* t = (int*) malloc(sizeof(int)); int* y = (int*) malloc(sizeof(int)); int* x = (int*) malloc(sizeof(int)); *x = 3; *y = 5; z = *x + *y; w = *y; *x = z; free(x); *t = 2; y = &z; x = y; free(t); printf("*x=%d, *y=%d, z=%d, w=%d\n", *x, *y, z, w); September 18, 2017 Hassan Khosravi / Geoffrey Tien 12

Dynamic allocation of a 2D array See dma_2d.c for details int dim_row = 3; int dim_col = 5; int** myarray; // pointer to a pointer stack heap myarray September 18, 2017 Hassan Khosravi / Geoffrey Tien 13

Stack memory vs heap memory Stack fast access allocation/deallocation and space automatically managed memory will not become fragmented Heap variables accessible outside declaration scope no (practical) limit on memory size variables can be resized local variables only limit on stack size (OSdependent) variables cannot be resized (relatively) slower access no guaranteed efficient use of space memory management is programmer's responsibility September 18, 2017 Hassan Khosravi / Geoffrey Tien 14

Strings What is a C string? an array (string) of char that terminates in a null character ('\0') Different ways to create strings char an_array[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; char str[somesize] = "A string of char"; This automatically gives a null char at the end char* another_string = "A string of char"; This automatically gives a null char at the end September 18, 2017 Hassan Khosravi / Geoffrey Tien 15

String length How long is a piece of string? C provides a group of functions for string processing, declared in a header string.h #include <string.h> Calculating length size_t strlen(const char* s); size_t is an unsigned data type defined by several C/C++ standards char mystring[] = "Hello there"; int length; length = strlen(mystring); printf("the string '%s' has %d letters\n", mystring, length); September 18, 2017 Hassan Khosravi / Geoffrey Tien 16

String comparison Comparing integers and characters: use == int a = 6; int b = 7; if (a == b) {... } To compare strings in C: char a = 'a'; char b = 'b'; if (a == b) {... } int strcmp(const char* str1, const char* str2); int strncmp(const char* str1, const char* str2, size_t num); char string1[] = "Hello"; char string2[] = "Hello there"; int length; length = strlen(string1); if (strncmp(string1, string2, length) == 0) { printf("the first %d letters of %s and %s are the same\n", length, string1, string2); } else { printf("not the same\n"); } September 18, 2017 Hassan Khosravi / Geoffrey Tien 17

String searching Searching check if a string contains another string char* strstr(const char* haystack, const char* needle); locates the first occurrence in haystack of the entire needle string, or NULL if not found char string1[] = "feed"; char string2[] = "Don't feed the bear!"; char* result = NULL; result = strstr(string2, string1); printf("%s\n", result); result = strstr(string2, "Please"); if (result == NULL) { printf("not found\n"); } feed the bear! Not found September 18, 2017 Hassan Khosravi / Geoffrey Tien 18

String concatenation Concatenation int strncat(char* s1, const char* s2, size_t n); appends no more than n bytes from s2 to the end of s1 The initial byte of s2 overwrites the null byte of s1 A terminating null byte is appended to the result returns s1 (with s2 concatenated) char* empty_string; char a_long_string[128] = "These "; strcat(a_long_string, "strings "); strcat(a_long_string, "are "); empty_string = strcat(a_long_string, "concatenated!"); printf("%s\n", empty_string); September 18, 2017 Hassan Khosravi / Geoffrey Tien 19

String copying Copying copies not more than n bytes from the string pointed to by s2 to the string pointed to by s1 returns s1 char* strncpy(char* s1, const char* s2, size_t n); char a_str[] = "Make the news."; int length = strlen(a_str); char* other_str = (char*) malloc(length+1); // why +1? strcpy(other_str, a_str); a_str[0] = 'F'; printf("a_str = %s\notherstr = %s\n", a_str, other_str); September 18, 2017 Hassan Khosravi / Geoffrey Tien 20

Readings for this lesson Thareja Appendices A, B, E, Chapter 4 Next class: Thareja, Chapter 5 September 18, 2017 Hassan Khosravi / Geoffrey Tien 21