16.216 ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 32: Dynamic memory allocation
ECE Application Programming: Lecture 32 Lecture outline Announcements/reminders No lecture Wednesday Program 9 and 10 posted Program 9 due 12/2 Program 10 due 12/9 Will count 9 of 10 programs; drop lowest score Grades done through Program 6 Regrade deadline for outstanding programs: end of semester (12/9) Today’s class Dynamic memory allocation 4/25/2017 ECE Application Programming: Lecture 32
Justifying dynamic memory allocation Data structures (i.e., arrays) usually fixed size Array length set at compile time Can often lead to wasted space May want ability to: Choose amount of space needed at run time Allows program to determine amount Modify size as program runs Data structures can grow or shrink as needed Dynamic memory allocation allows above characteristics 4/25/2017 ECE Application Programming: Lecture 32
Allocation functions (in <stdlib.h>) All return pointer to allocated data of type void * (no base type—just an address) Must cast to appropriate type Arguments of type size_t: unsigned integer Basic block allocation: void *malloc(size_t size); Allocate block and clear it: void *calloc(size_t nmemb, size_t size); Resize previously allocated block: void *realloc(void *ptr, 4/25/2017 ECE Application Programming: Lecture 32
Basic allocation with malloc() void *malloc(size_t size); Allocates size bytes; returns pointer Returns NULL if unsuccessful Example: int *p; p = malloc(10000); if (p == NULL) { /* Allocation failed */ } 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Type casting All allocation functions return void * Automatically type cast to appropriate type Can explicitly perform type cast: int *p; p = (int *)malloc(10000); Some IDEs (including Visual Studio) strictly require type cast 4/25/2017 ECE Application Programming: Lecture 32
Allocating/clearing memory: calloc() void *calloc(size_t nmemb, size_t size); Allocates (nmemb * size) bytes Sets all bits in range to 0 Returns pointer (NULL if unsuccessful) Example: integer array with n values int *p; p = (int *)calloc(n, sizeof(int)); 4/25/2017 ECE Application Programming: Lecture 32
Resizing allocated space: realloc() void *realloc(void *ptr, size_t size); ptr must point to previously allocated space Will allocate size bytes and return pointer size = new block size Rules: If block expanded, new bytes aren’t initialized If block can’t be expanded, returns NULL; original block unchanged If ptr == NULL, behaves like malloc() If size == 0, will free (deallocate) space Example: expanding array from previous slide p = (int *)realloc(p, (n+1)*sizeof(int)); 4/25/2017 ECE Application Programming: Lecture 32
Deallocating memory: free() All dynamically allocated memory should be deallocated when you are done using it Returns memory to list of free storage Once freed, program should not use location Deallocation function: void free(void *ptr); Example: int *p; p = (int *)malloc(10000); ... free(p); 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Application: arrays One common use of dynamic allocation: arrays Can determine array size, then create space Use sizeof() to get # bytes per element Array notation can be used with pointers int i, n; int *arr; printf("Enter n: "); scanf("%d", &n); arr = (int *)malloc(n * sizeof(int)); for (i = 0; i < n; i++) arr[i] = i; 4/25/2017 ECE Application Programming: Lecture 32
Example: what does program print? void main() { int *arr; int n, i; n = 7; arr = (int *)calloc(n, sizeof(int)); for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); n = 3; arr = (int *)realloc(arr, n * sizeof(int)); for (i = 0; i < n; i++) { arr[i] = i * i; } n = 6; arr = (int *)realloc(arr, n * sizeof(int)); for (i = 0; i < n; i++) { arr[i] = 10 - i; printf("%d ", arr[i]); } free(arr); 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Solution Output: 0 0 0 0 0 0 0 0 1 4 10 9 8 7 6 5 4/25/2017 ECE Application Programming: Lecture 32
Pitfalls: memory leaks Changing pointers leaves inaccessible blocks Example: p = malloc(1000); q = malloc(1000); p = q; Block originally accessed by p is “garbage” Won’t be deallocated—wasted space Solution: free memory before changing pointer free(p); 4/25/2017 ECE Application Programming: Lecture 32
Pitfalls: dangling pointers free() doesn’t change pointer Only returns space to free list Pointer is left “dangling” Holds address that shouldn’t be accessed Solution: assign new value to pointer Could reassign immediately (as in previous slide) Otherwise, set to NULL free(p); p = NULL; 4/25/2017 ECE Application Programming: Lecture 32
Dynamically allocated strings Strings arrays of characters Basic allocation: based on string length sizeof(char) is always 1 Need to account for null character Example: copying from s to str char *str = (char *)malloc(strlen(s) + 1); strcpy(str, s); Note: dynamically allocated strings must be deallocated when you are done with them 4/25/2017 ECE Application Programming: Lecture 32
Dynamically allocated 2D arrays Think of each row as 1D array 2D array: an array of 1D arrays Since array is technically a pointer, 2D array can be implemented as array of pointers Data type: “pointer to pointer” Example: int **twoDarr; 1st dimension depends on # rows twoDarr = (int **)malloc(nRows * sizeof(int *)); 2nd dimension depends on # columns Must allocate for each row for (i = 0; i < nRows; i++) twoDarr[i] = (int *)malloc(nCols * sizeof(int)); 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Example Complete each of the following functions char *readLine(): Read a line of data from the standard input, store that data in a dynamically allocated string, and return the string (as a char *) Hint: Read the data one character at a time and repeatedly reallocate space in the string int **make2DArray(int total, int nR): Given the total number of values and number of rows to be stored in a two-dimensional array, determine the appropriate number of columns, allocate the array, and return its starting address Note: if nR does not divide evenly into total, round up. In other words, an array with 30 values and 4 rows should have 8 columns, even though 30 / 4 = 7.5 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Solution char *readLine() { char c; // Input character char *str = NULL; // String to hold line int n = 1; // Length of str // Repeatedly store character in str until // '\n' is read; resize str to hold char while ((c = getchar()) != '\n') { str = (char *)realloc(str, n+1); str[n-1] = c; n++; } str[n-1] = '\0'; // Null terminator return str; 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Solution (continued) int **make2DArray(int total, int nR) { int **arr; // 2-D array int nCols; // # of columns int i; // Row index // Calculate nCols; round up if nR does not divide evenly nCols = total / nR; if ((total % nR) != 0) nCols++; // Allocate array--first array of rows, then each row arr = (int **)malloc(nR * sizeof(int *)); for (i = 0; i < nR; i++) arr[i] = (int *)malloc(nCols * sizeof(int)); return arr; } 4/25/2017 ECE Application Programming: Lecture 32
ECE Application Programming: Lecture 32 Next time Dynamically allocated data structures (Monday, 11/30) Reminders: No lecture Wednesday Program 9 and 10 posted Program 9 due 12/2 Program 10 due 12/9 Will count 9 of 10 programs; drop lowest score Grades done through Program 6 Regrade deadline for outstanding programs: end of semester (12/9) 4/25/2017 ECE Application Programming: Lecture 32