1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "nullpointer_dereference.h"
17 
18 #include <cstdio>
19 #include <memory>
20 #include <vector>
21 
22 using namespace OHOS::HiviewDFX;
23 
TestNullPointerDereferenceCrash0()24 int TestNullPointerDereferenceCrash0()
25 {
26     std::shared_ptr<NullPointerDereference> testcase = nullptr;
27     testcase->Print(); // may not crash
28     testcase->PrintMemberValue(); // crash here
29     return 0;
30 }
31 
TestNullPointerDereferenceCrash1()32 int TestNullPointerDereferenceCrash1()
33 {
34     auto testcase = std::make_shared<NullPointerDereference>();
35     testcase.reset();
36     testcase->Print(); // may not crash
37     return 0;
38 }
39 
TestNullPointerDereferenceCrash2()40 int TestNullPointerDereferenceCrash2()
41 {
42     auto testcase = std::make_shared<NullPointerDereference>();
43     testcase.reset();
44     testcase->PrintMemberValue(); // crash here
45     return 0;
46 }
47 
TestNullPointerDereferenceCrash3()48 int TestNullPointerDereferenceCrash3()
49 {
50     std::vector<std::weak_ptr<NullPointerDereference>> refs;
51     auto ref = refs.front(); // crash here
52     if (auto sharedRef = ref.lock()) {
53         printf("TestNullPointerDereferenceCrash3:%p:\n", sharedRef.get());
54     }
55     return 0;
56 }
57 
58 namespace OHOS {
59 namespace HiviewDFX {
Print() const60 void NullPointerDereference::Print() const
61 {
62     printf("NullPointerDereference::Print\n");
63 }
64 
PrintMemberValue() const65 void NullPointerDereference::PrintMemberValue() const
66 {
67     printf("NullPointerDereference::PrintMemberValue:\n");
68     printf("%d:\n", intTypeValue_);
69     printf("%d:\n", intTypeValue0_);
70 }
71 } // namespace HiviewDFX
72 } // namespace OHOS
73