Lab_memory
CS225 - Data Structures
If we run the program it may or may not complete without errors.
int main(){
int * arr = new int[100];
return arr[100];
}
1
2
3
4
What happens if we run valgrind? �valgrind ./main
Valgrind - a programming tool for memory debugging, memory leak detection, and profiling.
We will always check for memory errors and leaks on your assignments unless specified
int main(){
int * arr = new int[100];
return arr[100];
}
1
2
3
4
Example 1
What is wrong with this code?
int main(){
int * arr = new int[100];
return arr[100];
}
1
2
3
4
Out-of-bounds access to heap, stack, and globals. This error occurs when you allocate some memory and then try to access a region outside your allocated space.
int main(){
int * arr = new int[100];
return arr[100];
}
1
2
3
4
int main(){
int * arr = new int[100];
return arr[100];
}
1
2
3
4
int main(){
int x;
cout << x << endl;
}
1
2
3
4
Example 2 - Use of an uninitialized value.
int main(){
int * x = new int;
delete x;
delete x;
}
1
2
3
4
5
Example 3 - Invalid free error
Destructor
class Animal{
Animal();
~Animal();
}
Animal::Animal(){}
Animal::~Animal(){}
Animal.cpp
Animal.h
class A{
private:
int *n;
public:
A(int n1);
~A();
};
A::A(int n1){
n = new int(n1);
}
A::~A(){
delete n;
}
How will you change destructor if n was array of integers?
class A{
private:
int *n;
public:
A(int n1);
~A();
};
A::A(int n1){
n = new int(n1);
}
A::~A(){
delete n;
}
How will you change destructor if n was array of integers?
delete[]
int main(){
int * x = new int[6];
delete x;�}
1
2
3
4
Example 4 - Mismatched free() / delete / delete []
int main(){
int * arr = new int[10];
int * x = new int;
int * y;
arr[0] = *y;
delete arr;
delete x;
delete y;
return 0;
}
1
2
3
4
5
6
7
8
9
10
Spot the errors!
int main(){
int * arr = new int[10];
int * x = new int;
int * y;
arr[0] = *y; // y not initialized
delete arr; // Wrong delete, should be delete[] arr
delete x;
delete y; // Should not delete, not on heap return 0;
}
1
2
3
4
5
6
7
8
9
10
Spot the errors (Solution)
Tip: Valgrind output can get long
If necessary pipe the output of Valgrind to a file
valgrind ./exec &> log.txt
Tip: Read the Doxygen before beginning!
Make sure you understand what the code base is supposed to do!
The Allocator class takes as input Students and Rooms
Tip: Read the Doxygen before beginning!
Make sure you understand what the code base is supposed to do!
Students are loaded into Letter groups!
Tip: Read the Doxygen before beginning!
Make sure you understand what the code base is supposed to do!
Rooms store collections of Letters and have a capacity