Are there any tools to warn possible misusage of delete or delete []?
-
26-06-2021 - |
Question
I think I am clear on the difference between delete and delete []. The question I am asking here is: sometimes I do have typo and use the wrong one. Then it may or may not crash and normally ends up with hours of debugging.
I wish gcc can detect and give warning on possible misusage on a few simplest cases. I still have to use "new float[size]" from time to time because of legacy functions that I need to call, so I am more interested in find an error checking tool to catch part of these mistakes.
Solution
I wish gcc can detect and give warning on possible misuage on a few simplest cases.
Use valgrind.
I still have to use
new float[size]
from time to time because of legacy functions that I need to call
No, you don't. If a legacy function wants a pointer to the first element of an array of floats, do this:
std::vector<float> numbers(10);
legacy_func(&numbers[0]);
Don't do this:
float *numbers = new float[10];
legacy_func(numbers);
delete[] numbers;
OTHER TIPS
You may be able to put your floats in a std::vector<float>
and then pass front()
or &front()
to those legacy functions. I'm not sure this is guaranteed to work by the standard, but it ought to work in common implementations.
If you have C++11 library support and size
is known at compile time, std::array<float, size>
will be more efficient.