Copy from the "zero-based JSON library tutorial", Mark First, and then slowly study.
======== Reference Split Line ========
Under Linux, OS X, we can use the Valgrind tool (Apt-get install Valgrind, Brew install valgrind). We do not have to modify the code at all, just at the command line:
$ valgrind --leak-check=full ./leptjson_test
$ valgrind--leak-check=full./leptjson_test==22078==Memcheck, a memory error detector==22078Copyright (C)2002- -, and GNU GPL'd, by Julian Seward et al.==22078= = Using valgrind-3.11.0and Libvex; Rerun With-h forCopyrightInfo==22078= = Command:./leptjson_test==22078== --22078--run:/usr/bin/dsymutil"./leptjson_test" the/ the(100.00%) passed==22078== ==22078==HEAP SUMMARY:==22078==inchUse at exit: -,728bytesinch 209blocks==22078= = Total Heap Usage:301Allocs, theFrees, the,966Bytes Allocated==22078== ==22078==2bytesinch 1Blocks is definitely lostinchLoss record1Of -==22078= = at0x100012ebb: malloc (inch/usr/local/cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)==22078= = by0x100008f36: Lept_set_string (LEPTJSON.C:208)==22078= = by0x100008415: Test_access_boolean (test.c:187)==22078= = by0x100001849: Test_parse (test.c:229)==22078= = by0X1000017A3: Main (test.c:235)==22078==
It discovered that in Test_access_boolean (), the 2 bytes ("a") allocated by lept_set_string () were leaked.
Valgrind also has many features, such as the ability to discover uninitialized variables. If we forget to call Lept_init (&V) in the application or test program, then the value of V.type is not initialized, its value is indeterminate (indeterministic), and some functions have problems reading that value:
Static void Test_access_boolean () { lept_value v; /* * /lept_set_string ("a"1); ...}
This error sometimes works correctly when tested (just V.type is set to 0), which makes us think the program is correct, but it may crash on some machines after it is released. This false illusion is very dangerous, we can use the Valgrind can be automatically measured out:
$ valgrind--leak-check=full./leptjson_test ...==22174==Conditional Jump or move depends on uninitialised value (s)==22174= = at0x100008b5d: Lept_free (LEPTJSON.C:164)==22174= = by0x100008f26: Lept_set_string (LEPTJSON.C:207)==22174= = by0x1000083fe: Test_access_boolean (test.c:187)==22174= = by0x100001839: Test_parse (test.c:229)==22174= = by0x100001793: Main (test.c:235)==22174==
It finds that Lept_free () relies on an uninitialized value to jump, which is v.type, and the error is along the self-test_access_boolean ().
When writing unit tests, you should consider which order of execution will have a chance of error, such as memory-related errors. Then we can take the steps of TDD, the shilling test fails (in memory tool detection), fix the code, and then confirm the success of the test.
Linux Memory leak checker tool Valgrind