Why this matters
In C++, your code can compile and still be unsafe. It may pass your sample test, then crash on a judge, a friend’s laptop, or during a demo.
This lesson is about avoiding the common break points first: bad input handling, out-of-range access, uninitialised values, and integer surprises.
One rule
Do not trust memory, input, or indexes by default. Check sizes, initialise values, and make invalid states hard to reach.
Safe C++ is not fancy C++. It is boring code that behaves the same way every time you run it.
Write safer basics
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 6 done
Silent wrong code
A common beginner mistake is assuming the input is always perfect. In a project repo, your sample data may be clean, but users can type empty input, text instead of numbers, or a negative value.
Another mistake is reading n items and then accessing v[n]. The last valid index is n - 1. C++ may not stop you. It may just give garbage or crash later.
Before and after
This small program reads daily expenses and prints the total. The safe version checks input, rejects negative counts, and never reads outside the vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 0;
if (!(cin >> n)) {
cout << "Invalid count\n";
return 1;
}
if (n < 0) {
cout << "Count cannot be negative\n";
return 1;
}
vector<int> expenses(n);
for (int i = 0; i < n; i++) {
if (!(cin >> expenses[i])) {
cout << "Invalid expense\n";
return 1;
}
if (expenses[i] < 0) {
cout << "Expense cannot be negative\n";
return 1;
}
}
long long total = 0;
for (int amount : expenses) {
total += amount;
}
cout << total << "\n";
return 0;
}
// Sample input:
// 4
// 120 50 30 200
// Output:
// 400Use AI carefully
You can ask ChatGPT or Gemini to review your C++ for undefined behaviour. Paste a function and ask: “Find uninitialised variables, out-of-range access, integer overflow risk, and bad input handling.”
Do not accept the answer blindly. Check each suggestion against your code. AI often suggests style changes too. Keep the fixes that prevent real bugs.
Your repo habit
From lesson one, keep sample input near your code. A future internship reviewer should be able to run your program without guessing what to type.
For now, a simple input.txt is enough. Later you will improve build instructions and README structure.
// input.txt
4
120 50 30 200Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done