Lab_conway
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 Snapshot class handles the visualization of a single frame of Game
Tip: Read the Doxygen before beginning!
Make sure you understand what the code base is supposed to do!
The Game class steps through different rounds, producing Snapshots
Once finished, post your animations on Discord!
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
Note: In the following examples, assume we are in an infinite empty grid
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules
(Optional) Conway Game of Life Rules