/
nullpointer.cpp
41 lines (37 loc) · 998 Bytes
/
nullpointer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/***********************************************************
* Student No: 12815482 *
* Student Name: Tirthankar Bhaumik *
* Course: MSc Computing for Financial Services *
* Assignment: Final Assignment 4 *
* Objective: Demo of CPPCHECK tool - Null Pointer Exception*
************************************************************/
void f1(struct fred_t *p)
{
// dereference p and then check if it's NULL
int x = p->x;
if (p)
do_something(x);
}
void f2()
{
const char *p = NULL;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
p = str + i;
break;
}
}
// p is NULL if str doesn't have a space. If str always has a
// a space then the condition (str[i] != '\0') would be redundant
return p[1];
}
void f3(int a)
{
struct fred_t *p = NULL;
if (a == 1)
p = fred1;
// if a is not 1 then p is NULL
p->x = 0;
}