The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #18
Programming with C++
new and delete, arrays, array vs vector
Warm up
-
What do we gain by using heap memory allocation?
-
What do we lose by using heap memory allocation?
-
What are some differences between pointers and references?
-
What does the following statement do? What are the types of the four variables below?
auto ptr = new int( 42 );
auto i = *ptr;
auto j = &i;
auto k = &*ptr;
-
What's an address space?
Warm up
ptr (0xff000070)
j (0xffffffe4)
k (0xff000070)
i (42)
Stack
42
Heap
0xff000070
auto ptr = new int( 42 );
auto i = *ptr;
auto j = &i;
auto k = &*ptr;
0xffffffe8
0xffffffe4
0xffffffdc
0xffffffd4
Exercise 1
Replace question marks with "stack", "heap" or "global", according to your understanding of the language rules
-
Open the exercise template
-
Write your code, press Run to test
-
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
-
Click on the corresponding option in the "Lab18 exercises" poll in #general
new and delete
new type
- attempts to allocate dynamic storage of the specified type
- returns a pointer to type
- can fail with an exception if there isn't enough memory available
- allocated memory is default-initialized (default constructor is called for user-defined types, built-in types are left uninitialized)
new type()
new type( value )
- same as above, but memory is direct-initialized with the provided value (a corresponding constructor is called for user-defined types, built-in types are initialized with the value/zero-initialized if no value has been provided)
delete ptr
- deallocates storage previously allocated by a new
- if ptr points to a user-defined type with a non-trivial destructor, the destructor is called
- has no effect if ptr is a null pointer
Arrays
int main() {
int a[10] = { 5, -1, 0, 12,
-7, 13, 99, 64,
11, -22 };
std::cout << a[0] << std::endl;
std::cout << a[1] << std::endl;
}
a[6]
Stack
a[5]
a[4]
a[3]
a[2]
a[1]
a[0]
a[7]
a[8]
a[9]
Array vs vector
int main() {
std::vector<int> a = {
5, -1, 0, 12,
-7, 13, 99, 64,
11, -22 };
std::cout << a[0] << std::endl;
std::cout << a[1] << std::endl;
}
a[6]
Heap
a[5]
a[4]
a[3]
a[2]
a[1]
a[0]
a[7]
a[8]
a[9]
a (ptr=0xff000050, size=10)
Stack
0xff000050
Programming with C++, Fall 2019, Lecture #18
By Aleksey Gurtovoy
Programming with C++, Fall 2019, Lecture #18
new and delete, arrays, array vs vector
- 518