Skip to content

Commit 4de43e1

Browse files
committed
C++: Add the examples to the test.
1 parent f64743e commit 4de43e1

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

cpp/ql/test/query-tests/Security/CWE/CWE-570/IncorrectAllocationErrorHandling.expected

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@
1616
| test.cpp:151:9:151:24 | new | This allocation cannot throw. $@ is unnecessary. | test.cpp:152:15:152:18 | { ... } | This catch block |
1717
| test.cpp:199:15:199:35 | new | This allocation cannot throw. $@ is unnecessary. | test.cpp:201:16:201:19 | { ... } | This catch block |
1818
| test.cpp:212:14:212:34 | new | This allocation cannot throw. $@ is unnecessary. | test.cpp:213:34:213:36 | { ... } | This catch block |
19+
| test.cpp:246:17:246:31 | new[] | This allocation cannot return null. $@ is unnecessary. | test.cpp:247:8:247:12 | ! ... | This check |

cpp/ql/test/query-tests/Security/CWE/CWE-570/test.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,3 +233,54 @@ void test_operator_new_without_exception_spec() {
233233
int* p = new(42, std::nothrow) int; // GOOD
234234
if(p == nullptr) {}
235235
}
236+
237+
namespace std {
238+
void *memset(void *s, int c, size_t n);
239+
}
240+
241+
// from the qhelp:
242+
namespace qhelp {
243+
// BAD: the allocation will throw an unhandled exception
244+
// instead of returning a null pointer.
245+
void bad1(std::size_t length) noexcept {
246+
int* dest = new int[length];
247+
if(!dest) {
248+
return;
249+
}
250+
std::memset(dest, 0, length);
251+
// ...
252+
}
253+
254+
// BAD: the allocation won't throw an exception, but
255+
// instead return a null pointer. [NOT DETECTED]
256+
void bad2(std::size_t length) noexcept {
257+
try {
258+
int* dest = new(std::nothrow) int[length];
259+
std::memset(dest, 0, length);
260+
// ...
261+
} catch(std::bad_alloc&) {
262+
// ...
263+
}
264+
}
265+
266+
// GOOD: the allocation failure is handled appropriately.
267+
void good1(std::size_t length) noexcept {
268+
try {
269+
int* dest = new int[length];
270+
std::memset(dest, 0, length);
271+
// ...
272+
} catch(std::bad_alloc&) {
273+
// ...
274+
}
275+
}
276+
277+
// GOOD: the allocation failure is handled appropriately.
278+
void good2(std::size_t length) noexcept {
279+
int* dest = new(std::nothrow) int[length];
280+
if(!dest) {
281+
return;
282+
}
283+
std::memset(dest, 0, length);
284+
// ...
285+
}
286+
}

0 commit comments

Comments
 (0)