简体   繁体   English

如何快速检查和分析代码中的错误(C ++)

[英]How to quickly inspect and analyse code for bugs (C++)

Let suppose you've just written some big code, it compiles and everything's fine...But in the end, the result is not the expected or the code simply crashes. 假设您已经编写了一些大代码,可以编译并且一切都很好……但是最后,结果不是预期的,或者代码只是崩溃了。 There's some bug in the code, and you have to look for it in ALL (nearly) the lines... 代码中有一些错误,您必须在所有(几乎所有)行中进行查找...

One way is to just put cout/printf after each loop/important function so to see how the variables are changing and where is the mistake. 一种方法是将cout / printf放在每个循环/重要函数之后,以查看变量如何变化以及错误在哪里。 This apparently works, and using it i've discovered some of my usual mistakes while coding. 这显然是可行的,并且使用它我在编码时发现了一些我通常的错误。 But if there are a lot of variables and a lot of functions/loops - putting cout in each of them for every variable is nearly impossible. 但是,如果有很多变量和很多函数/循环-将cout放入每个变量几乎是不可能的。 There must be some other way to do this. 必须有其他方法可以做到这一点。

That's why I am asking here - Is there any way to track the values of the variables in the code other than the silly method described above ? 这就是为什么我要在这里问-除了上述愚蠢的方法之外,还有什么方法可以跟踪代码中变量的值吗? I've heard debugging but not really sure what exactly does it mean and what does it do. 我听说过调试,但不确定是什么意思和作用。

Use a Debugger 使用调试器

There's a debugger for most (if not all) popular C++ development environments. 大多数(如果不是全部)流行的C ++开发环境都有一个调试器。 I'd be of the opinion that you cannot develop non-trivial code without one. 我认为,如果没有一个,您将无法开发非平凡的代码。

(Yes I'm aware there's a movement in TDD that states if you've sufficient test coverage you don't need a debugger. Which is complete @rse IMHO) (是的,我知道TDD中有一种趋势表明,如果您具有足够的测试覆盖率,则不需要调试器。这是完整的@rse IMHO)

One way is to just put cout/printf after each loop/important function so to see how the variables are changing and where is the mistake. 一种方法是将cout / printf放在每个循环/重要函数之后,以查看变量如何变化以及错误在哪里。

That method is good if you can improve it. 如果您可以改进它,那将是很好的方法。 Instead of testing everything , you should make 而不是测试所有内容 ,您应该
it a habit to bisect the code (divide and conquer) until you locate the bug. 成为一个习惯, 平分直到找到错误的代码(分治)。
And of course you should learn how to use a debugger on your programing environment. 当然,您应该学习如何在编程环境中使用调试器。

What you use to debug depends on your environment. 用于调试的内容取决于您的环境。 In an IDE, you would usually use the IDE's builtin debugger, but if you're working at the commandline, GDB 's probably a good choice. 在IDE中,通常会使用IDE的内置调试器,但是如果在命令行中工作,则GDB可能是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM