Fast searching silly mistakes in C++: shortly and with examples

Правка en2, от dmkz, 2020-02-21 11:04:57

To find an error in the code you just need...

$$$\text{ }$$$

Firsly, you can check overflow of integer types, mistakes like = instead ==, writing a long long value in int and something else. It can be done in compile time with enabling of all available warnings. You can check your code fast there. Link have examples and you can read them. Warnings is not an errors, but sometimes can be.

Description of warnings can be found there.

List of used warnings

Secondly, you can test your solution in custom invocation. You should go to Custom invocation, place your code and test on samples and custom testswith compiler Clang++17 Diagnostics. It is a magic, just try a few examples:

Integer overflow in multiplication
Integer overflow in left shift
Out of bounds vector or array

Next steps: with GNU G++ compiler use a debug version of stardard library with next macroses:

#define _GLIBCXX_DEBUG 1
#define _GLIBCXX_DEBUG_PEDANTIC 1
#define _FORTIFY_SOURCE 2

You should to run a few tests for your code to catch mistakes in runtime. Examples:

Out of bounds vector
Attempt to dereference a singular iterator
Merge two partially sorted arrays
Unexpected reallocation of memory in vector

If you are solving a problem, try to test it by yourself on your small testcases, or brute all testcases and compare results of fast algorithm with results of naive but correct algorithm.

Also, you can use assert(condition); for check invariants or conditions. Even if you think that it will be always correct, because in practice small mistake in logic will leads to assertion failures. If the condition is false, you will see verdict "Runtime error" for you submission.

First example of using assert
Second example of using assert

Next, you can use a method called Method of intent look: when you try to detect what is wrong by reading you code. You should write a easy readable code for it.

Also, you can try to output some variables that u use in program. These macroses will help efficiently output a debug information in console, for example, variables with their names, containers like std::vector<X> and std::set<X>, pairs like std::pair<X,Y>. You can extend their functionality, or now you know that it is possible and can search for a better macroses or creater it by yourself.

I recommend to read this blog about catching silly mistakes in GCC C++.

Теги #debug

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский dmkz 2020-02-21 11:04:57 10 Tiny change: 'deone.com/otq76E) will hel' -> 'deone.com/r7gCgv) will hel'
en1 Английский dmkz 2020-02-21 11:00:11 7243 Initial revision for English translation
ru3 Русский dmkz 2020-02-18 19:28:50 49
ru2 Русский dmkz 2020-02-18 19:24:41 41
ru1 Русский dmkz 2020-02-18 19:18:23 6919 Первая редакция (опубликовано)