dmkz's blog

By dmkz, history, 4 years ago, translation, In English

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++.

  • Vote: I like it
  • +77
  • Vote: I do not like it