Dynamic Memory Allocation Strings

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
Introduction to C programming
Outline Midterm results Static variables Memory model
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Insertion sort Loop invariants Dynamic memory
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Cinda Heeren / Geoffrey Tien
Day 03 Introduction to C.
Hassan Khosravi / Geoffrey Tien
ENEE150 Discussion 07 Section 0101 Adam Wang.
Hassan Khosravi / Geoffrey Tien
Day 03 Introduction to C.
Hassan Khosravi / Geoffrey Tien
CSCI206 - Computer Organization & Programming
Arrays in C.
Lecture 6 C++ Programming
CS157: Dynamic Memory Dynamic Memory 11/9/201804/25/06.
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CSCI206 - Computer Organization & Programming
14th September IIT Kanpur
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
Hassan Khosravi / Geoffrey Tien
EECE.2160 ECE Application Programming
Outline Defining and using Pointers Operations on pointers
Dynamic Memory A whole heap of fun….
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
Pointers and Arrays Beyond Chapter 16
7. Pointers, Dynamic Memory
Dynamic Memory A whole heap of fun….
COP 3330 Object-oriented Programming in C++
EECE.2160 ECE Application Programming
Dynamic Memory – A Review
Pointers.
SPL – PS2 C++ Memory Handling.
Chapter 16 Pointers and Arrays
Presentation transcript:

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

Hassan Khosravi / Geoffrey Tien 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

Hassan Khosravi / Geoffrey Tien 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? 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 Change code and recompile Wastes memory September 18, 2017 Hassan Khosravi / Geoffrey Tien

Hassan Khosravi / Geoffrey Tien 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

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

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

Hassan Khosravi / Geoffrey Tien Heap example stack heap int main() { int a; int *p = (int*) malloc(sizeof(int)); *p = 10; } a p 4931 4931 10 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

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

Allocating dynamic arrays From user input, variable array size #include <stdio.h> #include <stdlib.h> 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

Hassan Khosravi / Geoffrey Tien 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

Hassan Khosravi / Geoffrey Tien 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[2] = 7; stack heap Lost access to this array! 5 4 arr sz 7 See memory_leak.c September 18, 2017 Hassan Khosravi / Geoffrey Tien

Hassan Khosravi / Geoffrey Tien 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

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

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

Hassan Khosravi / Geoffrey Tien 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"; September 18, 2017 Hassan Khosravi / Geoffrey Tien

String length How long is a piece of string? C provides a group of functions for string processing, declared in a header string.h Calculating length size_t is an unsigned data type defined by several C/C++ standards #include <string.h> size_t strlen(const char* s); 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

Hassan Khosravi / Geoffrey Tien String comparison Comparing integers and characters: use == To compare strings in C: int a = 6; int b = 7; if (a == b) { ... } 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

Hassan Khosravi / Geoffrey Tien String searching Searching – check if a string contains another string locates the first occurrence in haystack of the entire needle string, or NULL if not found char* strstr(const char* haystack, const char* needle); 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

Hassan Khosravi / Geoffrey Tien String concatenation Concatenation 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) int strncat(char* s1, const char* s2, size_t n); 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

Hassan Khosravi / Geoffrey Tien 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

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