CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation
Why use Pointers? Share access to common data (hold onto one copy, everybody points to it) Flexibility (dynamic data structures) Precisely control allocation/deallocation ourselves
Passing Arrays as Arguments In function declaration / prototype use type [] or type * When calling the function, simply provide the name of the array as the argument In /C++, array name by itself evaluates to the starting address of the array C+ does implicitly keep track of the size of the array Thus either need to have the function only accept arrays of a certain size Or need to pass the size (length) of the array as another argument void add_1_to_array_of_10(int []); void add_1_to_array(int *, int); int main() { int data[10] = {9,8,7,6,5,4,3,2,1,0; add_1_to_array_of_10(data); cout << data[0] = << data[0] << endl; add_1_to_array(data,10); cout << data[9] = << data[9] << endl; return 0; void add_1_to_array_of_10(int my_array[]) { int i=0; for(i=0; i < 10; i++){ my_array[i]++; void add_1_to_array(int *my_array, int size) { int i=0; for(i=0; i < size; i++){ my_array[i]++;
Command Line Arguments int main(int argc, char *argv[]) {... > encrypt tweet.txt encrypted.txt argc = 3 argv[0] = encrypt argv[1] = tweet.txt argv[2] = encrypted.txt
Pointers as Function Return Value Pointer value (i.e. the address) is still passed-by-value (i.e. a copy is made) The value of y is CHANGED by doit() and that change is visible when we return. Address 0x0000000 System Memory (RAM) 0xffffffff Code for all functions Data for doit Data for doit (x=0x20bd4, x = 0x20bd4 i) and return i = 2 link Data for main Data for main (a=??, y=3, ptr=0x20bd4) a=5, y[0]=2,y[1]=5 and return link ptr=0x20bd4 System stack area int main() { int a, y[2]= {3,5, *ptr; // assume y @ 0x20bd4 // assume ptr ptr = y; a = *doit(ptr); cout << a= << a << endl; cout << y[0]= <<y[0]<< endl; return 0; //! Remember * in a type/ // declaration Remember * in means a type! pointer // declaration // variable means pointer! int // variable! doit(int *x) { int* int doit(int i; *x) { *x = *x - 1; int i; i = *x; *x = *x - 1; x++; i = *x; return x++; i; return x; Output: a=5 y[0]=2
Why use Pointers? Share access to common data (hold onto one copy, everybody points to it) Flexibility (dynamic data structures) Precisely control allocation/deallocation ourselves
Dynamic Memory Alloca/on I want an array for student scores but I don t know how many students we have un/l the user tells me What size should I use to declare my array? int scores[??] Doing the following is not supported by all C++ compilers: int num; cin >> num; int scores[num]; // compilers require the array size // to be statically known All compilers support alloca/ng memory dynamically (i.e. at run- /me)
8 Dynamic Variables Dynamic variables: created during execu/on C++ creates dynamic variables using pointers new and delete operators: used to create and destroy dynamic variables new and delete are reserved words in C++ C++ Programming: Program Design Including Data Structures, Sixth Edition
Dynamic Memory & the Heap Code usually sits at low addresses Global variables somewhere amer code System stack (memory for each func/on instance that is alive) Local variables Return link (where to return) etc. Heap: Area of memory that can be allocated and de- allocated during program execu/on (i.e. dynamically at run- /me) based on the needs of the program Heap grows downward, stack grows upward In rare cases of large memory usage, they could collide and cause your program to fail or generate an excep/on/error 0 fffffffc Memory Code Globals Heap Stack (area for data local to a function)
10 Operator new intexp is any expression evalua/ng to a posi/ve integer new allocates memory (a variable) of the designated type and returns a pointer to it The allocated memory is unini/alized C++ Programming: Program Design Including Data Structures, Sixth Edition
11 Operator new Example: p = new int; Creates a variable during program execu/on somewhere in memory Stores the address of the allocated memory in p To access allocated memory, use *p A dynamic variable cannot be accessed directly Because it is unnamed
C++ new & delete operators new allocates memory from heap followed with the type of the variable you want or an array type declara/on double *dptr = new double; int *myarray = new int[100]; can obviously use a variable to indicate array size returns a pointer of the appropriate type if you ask for a new int, you get an int * in return if you ask for a new array (new int[10]), you get an int ** in return delete returns memory to the heap followed by the pointer to the data you want to de- allocate delete dptr; use delete [] for arrays delete [] myarray;
Dynamic Memory Alloca/on int main() { int *scores; int num; cout << How many students? << endl; cin >> num; scores = new int[num]; // can now access scores[0].. scores[num-1]; return 0; int main() { int *scores; int num; cout << How many students? << endl; cin >> num; scores = new int[num]; // can now access scores[0].. scores[num-1]; delete [] scores return 0; 0 Code Globals Heap 20bc0 00 20bc4 00 20bc8 00 20bcc 00 20bd0 00 fffffffc local vars Memory new allocates: scores[0] scores[1] scores[2] scores[3] scores[4]
14 Operator delete delete only marks the memory space as deallocated Pointer variable may s/ll contain address of deallocated memory space If you try to access via the pointer, could result in corrup/ng data or termina/on Avoid this by sezng pointers to NULL amer delete opera/on C++ Programming: Program Design Including Data Structures, Sixth Edition
15 Operator delete Memory leak: previously allocated memory that cannot be reallocated To avoid a memory leak, when a dynamic variable is no longer needed, destroy it to deallocate its memory delete operator: used to destroy dynamic variables Syntax: C++ Programming: Program Design Including Data Structures, Sixth Edition
16 Dynamic Arrays Dynamic array: array created during program execu/on Example: int *p; p = new int[10]; *p = 25; stores 25 into the first memory location p++; //to point to next array component *p = 35; stores 35 into the second memory location C++ Programming: Program Design Including Data Structures, Sixth Edition
17 Dynamic Arrays Can use array notation to access these memory locations Example: p[0] = 25; p[1] = 35; Stores 25 and 35 into the first and second array components, respectively An array name is a constant pointer C++ Programming: Program Design Including Data Structures, Sixth Edition
18 Dynamic Two- Dimensional Arrays You can create dynamic mul/dimensional arrays Examples: declares board to be an array of four pointers wherein each pointer is of type int creates the rows of board declares board to be a pointer to a pointer C++ Programming: Program Design Including Data Structures, Sixth Edition
19 Problem: Create a function to ask the user to input test scores 1. The function should ask the user for the number of test scores 2. Dynamically create an array of that size 3. Then ask the user to enter in each test score. 4. Return a pointer to the array of test scores