Campus Academic Help provides practical C++ assignment assistance, helping students review code, identify errors, and resolve program crashes.
| Error stage | Common message or symptom | Difficulty |
|---|---|---|
| Compilation | Expected ';' before '}' |
Easy |
| Linking | Undefined reference |
Medium |
| Loading | Error while loading shared libraries |
Easy to identify |
| Execution | Segmentation fault |
Hard |
| Execution | Unhandled exception |
Medium |
| Any stage | Incorrect program output |
Very hard |
When debugging, first identify the stage where the error occurs. This helps narrow down whether the problem involves syntax, linking, the runtime environment, or program logic.
#include <iostream>
using namespace std;
int main() {
int* ptr = nullptr;
*ptr = 42;
return 0;
}
Here, ptr does not point to a valid integer. Dereferencing it causes undefined behavior and commonly results in a crash.
Common messages include:
Segmentation fault (core dumped).zsh: segmentation fault.Access violation.Common causes of segmentation faults:
g++ -g program.cpp -o program
gdb ./program
Then execute:
(gdb) run
(gdb) bt
The -g option adds debugging information, while bt displays the call stack and helps identify where the crash occurred.
int* ptr = nullptr;
if (ptr != nullptr) {
*ptr = 42;
}
Check array indexes before accessing elements:
int arr[5];
int index = userInput;
if (index >= 0 && index < 5) {
arr[index] = 10;
}
After deleting dynamically allocated memory, reset the pointer:
int* ptr = new int(10);
delete ptr;
ptr = nullptr;
Always ensure that pointers reference valid objects that are still alive and accessible.
undefined reference to `helper()'
collect2: error: ld returned 1 exit status
This means the program calls helper(), but the linker cannot find its implementation.
g++ main.cpp helper.cpp -o program
2. Declaring a function without defining it
Declaring a function in a header file does not automatically provide its implementation.
// helper.h
void helper();
Add the actual function definition in the appropriate source file.
3. Using an incorrect namespace
The declaration and definition must belong to the same namespace.
void utils::greet() {
cout << "Hello";
}
4. Missing a required library
External libraries must be included in the linking command. For example:
g++ program.cpp -o program -pthread
Some programs also require library options such as -lsqlite3 or -lsfml-graphics.
Example of a valid entry point:
int main() {
cout << "Hello World";
return 0;
}
Standard C++ requires main() to return int. Using void main() may cause a compilation error.
free(): double free detected in tcache 2
Aborted (core dumped)
Other messages include free(): invalid pointer and malloc(): corrupted top size.
int* ptr = new int(10);
delete ptr;
delete ptr; // Incorrect
After the first delete, the memory is released. Deleting it again causes undefined behavior.
int x = 5;
int* ptr = &x;
delete ptr; // Incorrect
The variable x was not allocated using new, so it must not be deleted.
int* arr = new int[3];
arr[5] = 100; // Invalid index
delete[] arr;
The array contains only three elements, with valid indexes 0, 1, and 2. Accessing index 5 can corrupt nearby memory and cause unexpected crashes.
int* a = new int;
delete a;
int* b = new int[10];
delete[] b;
For C-style allocation, use malloc() with free().
Reset pointers after deletion:
int* ptr = new int(10);
delete ptr;
ptr = nullptr;
#include <memory>
int main() {
std::unique_ptr<int> ptr =
std::make_unique<int>(10);
}
Use C++14 or later for make_unique. Prefer smart pointers when possible to reduce memory-management errors.
void leak() {
int* data = new int[1000];
return; // Memory is not released
}
Common causes of memory leaks:
g++ -g leak.cpp -o leak
valgrind --leak-check=full ./leak
Valgrind identifies memory leaks and provides information about where allocations occurred.
Its reports include:
g++ -fsanitize=address -g leak.cpp -o leak
./leak
AddressSanitizer can detect memory leaks on supported platforms, including Linux.
For safer memory management:
void recurse() {
recurse();
}
int main() {
recurse();
}
Every function call creates another stack frame. Repeated calls eventually exhaust the available stack memory.
Other common causes include:
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
2. Store large data structures on the heap
Use vector instead of unnecessarily large local arrays:
vector<int> big(5000000);
3. Replace deep recursion with iteration
long long sum(int n) {
long long total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
Using long long prevents integer overflow for large sums that exceed the typical int range.
An iterative approach is generally more reliable when a calculation requires a very large number of steps.
int x = 5
cout << x;
The missing semicolon after int x = 5 may cause an error on the following line.
2. Using an undeclared identifier
This happens when the compiler cannot recognize a name.
For example, using cout without including its required header can produce an error.
Solution:
#include <iostream>
using namespace std;
3. Forgetting header files
Include the appropriate header for each standard library component:
4. Type mismatches Assigning a string to an integer variable causes a type error. Incorrect:
int name = "Alex";
Correct:
#include <string>
string name = "Alex";
5. Mismatched braces
Every opening brace must have a corresponding closing brace. Modern editors can help identify unmatched braces.
6. Using assignment instead of comparison
if (x = 5) { } // Assignment
if (x == 5) { } // Comparison
Enable compiler warnings to detect suspicious assignments:
g++ -Wall -Wextra program.cpp -o program
int* makePtr() {
int local = 42;
return &local;
}
When the function ends, local no longer exists. The returned pointer therefore refers to an expired object, causing undefined behavior.
Solution: Return the value directly or use dynamically allocated memory with clear ownership. A smart pointer is a safer alternative.
#include <memory>
unique_ptr<int> makePtr() {
return make_unique<int>(42);
}
int* ptr;
*ptr = 10; // Invalid memory access
This may cause crashes or memory corruption.
Solution: Initialize pointers immediately.
int* ptr = nullptr;
ptr = new int(10);
Before dereferencing a pointer, ensure it references a valid object and manage its memory correctly.
terminate called after throwing an instance of 'std::out_of_range'
For example, accessing index 10 in a vector containing only three elements can throw std::out_of_range.
Common situations include:
operator[].These problems may cause undefined behavior or operating-system errors rather than C++ exceptions.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(int a, int b) {
if (b == 0) {
throw runtime_error("Division by zero");
}
return static_cast<double>(a) / b;
}
int main() {
try {
cout << divide(10, 4) << endl;
}
catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
The catch block displays an understandable error message instead of allowing the exception to terminate the program unexpectedly.
catch (const exception& e) {
cout << e.what() << endl;
}
Catching exceptions by value can cause object slicing, which may remove information from the original exception.
catch (const invalid_argument& e) {
cout << "That is not a number.";
}
catch (const out_of_range& e) {
cout << "That number is too big.";
}
catch (const exception& e) {
cout << e.what();
}
catch (...) {
cout << "Unknown error.";
}
Place specific exception types before broader base classes. The catch-all handler (catch (...)) should be used as a final fallback.
class InvalidGrade : public runtime_error {
public:
explicit InvalidGrade(const string& message)
: runtime_error(message) {}
};
This allows the program to report specific errors with meaningful messages.
Containers and smart pointers help prevent memory leaks because they automatically release resources when objects go out of scope, including during exception handling.
C++ uses destructors and resource-management techniques (RAII) rather than a Java-style finally block. It also generally does not require programmers to catch or declare exceptions.Start with the first error instead of focusing on the last one. Check the file name, line number, and complete message.
Compilation errors usually involve syntax or data types. Linking errors include messages such as undefined reference. Runtime errors include crashes, unhandled exceptions, and unexpected output.
Compiler warnings can identify uninitialized pointers, incorrect memory operations, infinite recursion, and other programming mistakes.
g++ -Wall -Wextra -g main.cpp -o main
Find the smallest input that triggers the error. Reducing the input makes the problem easier to investigate.
Use std::cerr to display variable values and execution details during debugging. It is typically unbuffered, so diagnostic messages can appear even when a program crashes. Check array indexes, loop conditions, and variable values to identify unexpected behavior. The assert statement can also verify assumptions during development. However, assertions may be disabled when compiled with -DNDEBUG, so important input validation should not rely on them alone.
Use GDB or the debugging tools available in VS Code, CLion, Visual Studio, and Code::Blocks. Set breakpoints and inspect variables to locate where the program behaves unexpectedly.
AddressSanitizer and Valgrind help identify invalid memory access and memory leaks.
g++ -fsanitize=address -g main.cpp -o main
./main
Recompile after every correction. Test previous inputs again to ensure the changes have not introduced additional problems.
g++ -Wall -Wextra -Wpedantic program.cpp -o program
These options identify suspicious code, unused variables, and other potential mistakes. Adding -Werror treats warnings as errors.
Tool 2: Use GDB to Investigate Runtime Crashes
g++ -g program.cpp -o program
gdb ./program
Useful GDB commands include:
(gdb) run
(gdb) bt
(gdb) print var
(gdb) list
(gdb) break 42
(gdb) step
(gdb) catch throw
GDB helps inspect variables, set breakpoints, trace function calls, and investigate exceptions.
Tool 3: Use Valgrind to Find Memory Problems
g++ -g program.cpp -o program
valgrind --leak-check=full ./program
Valgrind detects memory leaks, invalid memory access, and reads from uninitialized memory. Its main drawback is that programs may run approximately 20–30 times slower.
Tool 4: Use AddressSanitizer for Quick Memory Checks
g++ -fsanitize=address -g program.cpp -o program
./program
AddressSanitizer detects many memory errors with less execution overhead than Valgrind. Its availability and leak-detection support depend on the operating system and compiler.
| Problem | Recommended tool |
|---|---|
| Compilation warnings | Compiler warnings |
| Segmentation fault | GDB |
| Unhandled exception | GDB with catch throw |
| Memory leaks | Valgrind or AddressSanitizer |
| Invalid memory access | AddressSanitizer or Valgrind |
| Incorrect output | cerr or GDB |
Learning these tools makes C++ debugging more systematic and less confusing.
Building these habits early helps students avoid common C++ errors and improve their programming skills. Campus Academic Help can also support students with programming concepts, code analysis, and debugging techniques.
Successful compilation does not guarantee correct logic or safe memory access. Runtime crashes may result from null pointers, invalid array indexes, division by zero, or stack overflow. Use GDB with the -g flag to investigate.
Vector manages its own memory, tracks its size, and supports dynamic resizing. Unlike raw arrays, its .at() method checks array bounds, making it a safer and more convenient choice for most C++ tasks.
It means the linker cannot find the required main() function. Check that main() exists, uses the correct lowercase spelling, and is included in the source file being compiled.
Use delete for a single object allocated with new and delete[] for an array allocated with new[]. Always match the deallocation method to the original allocation.
Use Valgrind with valgrind --leak-check=full ./program or AddressSanitizer with -fsanitize=address. On macOS, the leaks --atExit -- ./program command is another option.
No. Standard C++ requires main() to return int. Use int main() instead of void main().
RAII stands for Resource Acquisition Is Initialization. It allows objects to manage resources and release them automatically when their lifetimes end. Smart pointers, vector, and string use this principle to reduce memory-management errors.
You may be compiling a source file that does not contain main(). For multiple source files, compile them together: g++ main.cpp Student.cpp -o program. Alternatively, use the -c option to compile individual source files into object files.
NULL is a traditional macro that commonly expands to an integer constant such as 0. Introduced in C++11, nullptr is a dedicated null pointer literal. Prefer nullptr in modern C++ because it clearly identifies a null pointer and avoids certain ambiguities.
Whether your issue involves memory problems, loops, arrays, pointers, or debugging, our experts can help you identify and fix programming errors quickly.
Get C++ Assignment Help