Back to questionsWhat is wrong with this function that prints
JuniorDebuggingCommon
What is wrong with this function that prints a / b?
#include <iostream>
void print_ratio(int a, int b) {
int* ratio = new int{0};
if (b == 0) {
return;
}
*ratio = a / b;
std::cout << *ratio << '\n';
delete ratio;
}A leak: when b is 0, the function returns before delete ratio
- Expecting the int to be freed with
ratio: the end of a raw pointer's scope frees nothing, so an int whosedeleteis skipped stays allocated. - Expecting
delete[]:new int{0}creates one int, not an array, and a single object made bynewis freed with plaindelete.
- Why can't the program free this int later, after
print_ratiohas returned? - Why is
deletewritten in one destructor safer thandeletebefore everyreturn?
Fix
The int must be deleted on every path out of the function, and a destructor does that more reliably. std::unique_ptr deletes the int at any return:
#include <iostream>
#include <memory>
void print_ratio(int a, int b) {
std::unique_ptr<int> ratio = std::make_unique<int>(0);
if (b == 0) {
return;
}
*ratio = a / b;
std::cout << *ratio << '\n';
}Here the result could also live in a plain local variable int ratio: it does not need the heap at all.