So our professor gave us the task to debug this code. We can use the compiler and also try to use the gdb debugger.
#include <cstdlib>
#include <iostream>
#include <vector>
std::vector<int> reversed(const std::vector<int>& v) {
std::vector<int> result;
for (std::size_t i = v.size() - 1; i >= 0; --i) result.push_back(v[i]);
return result;
}
int main(int argc, char** argv) {
if (argc < 1) {
std::cerr << "Usage: " << argv[0] << " [number] [number]..." << std::endl;
return 1;
}
std::cerr << "Reading in " << (argc - 1) << " numbers from stdin"
<< std::endl;
std::vector<int> numbers;
for (std::size_t i = 0; i < argc; ++i) {
// atoi converts a string to a number
int number = std::stoi(argv[i]);
numbers.push_back(number);
}
std::cerr << "Reversing order of numbers" << std::endl;
auto reverse = reversed(numbers);
for (auto n : reverse) std::cout << n << std::endl;
}
When I use g++ -Wall debug-1.cc
I get this:
debug-1.cc: In function ‘int main(int, char**)’:
debug-1.cc:19:29: warning: comparison of integer expressions of different signedness: ‘std::size_t’ {aka ‘long unsigned int’} and ‘int’ [-Wsign-compare]
19 | for (std::size_t i = 0; i < argc; ++i) {
I also used the Debugger a put a breakpoint to lines 19, 20 and 21:
Breakpoint 1, main (argc=32767, argv=0x7ffff7fafee0 <std::wcerr>)
at debug-1.cc:11
11 int main(int argc, char** argv) {
(gdb) c
Continuing.
Reading in 0 numbers from stdin
Breakpoint 2, main (argc=1, argv=0x7fffffffdf08) at debug-1.cc:19
19 for (std::size_t i = 0; i < argc; ++i) {
(gdb) c
Continuing.
Breakpoint 3, main (argc=1, argv=0x7fffffffdf08) at debug-1.cc:21
21 int number = std::stoi(argv[i]);
(gdb) c
Continuing.
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
So, I guess the error lies somewhere between lines 19 and 21, but I really can't figure out what the error is. Hope you guys can help me out.
question from:
https://stackoverflow.com/questions/65919217/debugging-a-simple-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…