aboutsummaryrefslogtreecommitdiffstats
path: root/tests/src/test_preload.c
blob: 73690355f61ced82fa43c0b35103fb2184677e26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * @file   test_preload.c
 * @brief  Smoke test — call malloc once and print the returned pointer.
 *
 * Uses write(2) instead of printf to avoid stdio calling malloc
 * internally, which would pollute output under LD_PRELOAD.
 */

#include <stdlib.h>
#include <unistd.h>

/** @brief Write the hex representation of @p ptr to stdout. */
static void
_s_put_ptr (void *ptr)
{
  static const char hex[] = "0123456789abcdef";
  char buf[20];
  unsigned long v = (unsigned long)ptr;
  size_t i;

  if (!ptr)
    {
      write (1, "(nil)", 5);
      return;
    }
  i = sizeof (buf);
  while (v)
    {
      buf[--i] = hex[v % 16];
      v /= 16;
    }
  buf[--i] = 'x';
  buf[--i] = '0';
  write (1, buf + i, sizeof (buf) - i);
}

int
main (void)
{
  void *p = malloc (42);
  write (1, "malloc(42) = ", 13);
  _s_put_ptr (p);
  write (1, "\n", 1);
  free (p);
  return (0);
}