Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 29 additions & 15 deletions src/violations.cpp
Original file line number Diff line number Diff line change
@@ -1,27 +1,41 @@
// violations.cpp
// src/violations.cpp
#include <iostream>
#include <stdexcept>

class Unsafe {
int *p;
/* ─────────────────────────────────────────────
1. Guaranteed MEM50-CPP UseAfterFree hit
───────────────────────────────────────────── */
void use_after_free()
{
int* ptr = new int(42);
delete ptr; // pointer freed
*ptr = 7; // ❗ use-after-free (write) – MEM50-CPP triggers
}

/* ─────────────────────────────────────────────
2. Guaranteed ERR53-CPP hit in destructor
───────────────────────────────────────────── */
class Bad
{
int* p;
public:
Unsafe() { // Constructor throws without handling
p = new int(42);
if (*p == 42)
throw std::runtime_error("ERR51: unhandled exception"); // triggers ERR51-CPP
}
Bad() : p(new int(99)) {}

~Unsafe() noexcept { // Destructor references deleted memory
~Bad() noexcept // destructor must be noexcept for this rule
{
delete p;
int x = *p; // ERR53-CPP: value referenced after destruction
(void)x;
int val = *p; // ❗ dereference after delete – ERR53-CPP triggers
(void)val;
}
};

int main() {
int main()
{
try {
Unsafe u; // construction will throw
} catch (...) {
// Intentionally empty to keep program running
Bad b; // destructor runs at end of scope
use_after_free();
} catch (const std::exception&) {
// swallow any exception – not relevant for these rules
}
return 0;
}