summaryrefslogtreecommitdiffstats
path: root/winpr/libwinpr/crt/test/TestAlignment.c
blob: 07bac7f8d5f9b428bb9dd25186a9d1f4c1b10425 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <winpr/crt.h>
#include <winpr/windows.h>

int TestAlignment(int argc, char* argv[])
{
	void* ptr = NULL;
	size_t alignment = 0;
	size_t offset = 0;

	WINPR_UNUSED(argc);
	WINPR_UNUSED(argv);

	/* Alignment should be 2^N where N is a positive integer */

	alignment = 16;
	offset = 8;

	/* _aligned_malloc */

	ptr = winpr_aligned_malloc(100, alignment);

	if (ptr == NULL)
	{
		printf("Error allocating aligned memory.\n");
		return -1;
	}

	if (((size_t)ptr % alignment) != 0)
	{
		printf("This pointer, %p, is not aligned on %" PRIuz "\n", ptr, alignment);
		return -1;
	}

	/* _aligned_realloc */

	ptr = winpr_aligned_realloc(ptr, 200, alignment);

	if (((size_t)ptr % alignment) != 0)
	{
		printf("This pointer, %p, is not aligned on %" PRIuz "\n", ptr, alignment);
		return -1;
	}

	winpr_aligned_free(ptr);

	/* _aligned_offset_malloc */

	ptr = winpr_aligned_offset_malloc(200, alignment, offset);

	if (ptr == NULL)
	{
		printf("Error reallocating aligned offset memory.");
		return -1;
	}

	if (((((size_t)ptr) + offset) % alignment) != 0)
	{
		printf("This pointer, %p, does not satisfy offset %" PRIuz " and alignment %" PRIuz "\n",
		       ptr, offset, alignment);
		return -1;
	}

	/* _aligned_offset_realloc */

	ptr = winpr_aligned_offset_realloc(ptr, 200, alignment, offset);

	if (ptr == NULL)
	{
		printf("Error reallocating aligned offset memory.");
		return -1;
	}

	if (((((size_t)ptr) + offset) % alignment) != 0)
	{
		printf("This pointer, %p, does not satisfy offset %" PRIuz " and alignment %" PRIuz "\n",
		       ptr, offset, alignment);
		return -1;
	}

	/* _aligned_free works for both _aligned_malloc and _aligned_offset_malloc. free() should not be
	 * used. */
	winpr_aligned_free(ptr);

	return 0;
}