cunit-testingpointerscomparisonglib

How do I assert that two pointers are equal with GLib's testing framework?


I'm writing a unit test with GLib's testing framework where I want to check if two pointers point to the same place in memory. I do NOT want to compare the actual memory which they point to, so g_assert_cmpmem () would not be a solution.

My initial thinking was that pointers are integers, so I would just use g_assert_cmpint (). However, this generates errors as you cannot make integers from pointers without a cast:

In file included from /usr/include/glib-2.0/glib.h:89,
                 from ../src/pmos-tweaks/ms-tweaks-parser.h:11,
                 from ../src/pmos-tweaks/ms-tweaks-parser.c:11,
                 from ../tests/test-tweaks-parser.c:9:
../tests/test-tweaks-parser.c: In function ‘test_copy_setting’:
/usr/include/glib-2.0/glib/gtestutils.h:79:61: error: initialization of ‘guint64’ {aka ‘long unsigned int’} from ‘MsTweaksSetting *’ makes integer from pointer without a cast [-Wint-conversion]
   79 |                                              guint64 __n1 = (n1), __n2 = (n2); \
      |                                                             ^
../tests/test-tweaks-parser.c:53:3: note: in expansion of macro ‘g_assert_cmpuint’
   53 |   g_assert_cmpuint (setting, ==, setting_copied);
      |   ^~~~~~~~~~~~~~~~
/usr/include/glib-2.0/glib/gtestutils.h:79:74: error: initialization of ‘guint64’ {aka ‘long unsigned int’} from ‘MsTweaksSetting *’ makes integer from pointer without a cast [-Wint-conversion]
   79 |                                              guint64 __n1 = (n1), __n2 = (n2); \
      |                                                                          ^
../tests/test-tweaks-parser.c:53:3: note: in expansion of macro ‘g_assert_cmpuint’
   53 |   g_assert_cmpuint (setting, ==, setting_copied);
      |   ^~~~~~~~~~~~~~~~

Is the right solution here to just do a cast, or is there a better option?


Solution

  • There is no pointer equality assertion in GLib, so you should use g_assert_true():

    g_assert_true (setting == setting_copied)

    Note that you should not use g_assert(), as it will be compiled out if GLib is configured with G_DISABLE_ASSERT, and some distributions configure it this way.