所以我有两个指针:
unsigned char * a;
unsigned char * b;
假设我使用了 malloc 并且它们被分配了一定的大小。我想让指针地址的最低有效 4 位相同......但我真的不知道如何。
首先,我想从a
. 我尝试了类似的东西
int least = (&a) & 0x0f;
但我得到一个错误, & 是一个无效的操作数。我正在考虑分配更多b
并搜索与最低有效 4 位相同的地址,a
但我真的不知道该怎么做。
所以我有两个指针:
unsigned char * a;
unsigned char * b;
假设我使用了 malloc 并且它们被分配了一定的大小。我想让指针地址的最低有效 4 位相同......但我真的不知道如何。
首先,我想从a
. 我尝试了类似的东西
int least = (&a) & 0x0f;
但我得到一个错误, & 是一个无效的操作数。我正在考虑分配更多b
并搜索与最低有效 4 位相同的地址,a
但我真的不知道该怎么做。
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned char *a;
unsigned char *b;
a = malloc(8);
b = malloc(8);
if (((uintptr_t)a & 0x0F) == ((uintptr_t)b & 0x0F)) {
printf("Yeah, the least 4 bits are the same.\n");
} else {
printf("Nope, the least 4 bits are not the same.\n");
}
free(a);
free(b);
return EXIT_SUCCESS;
}
尝试这个:
int main()
{
unsigned char *a, *b;
a = malloc(32);
b = a + 16;
printf("%p %p\n", a, b); // You should see that their least significative
// 4-bits are equal
}
由于a
和b
相隔 16 个字节并且是连续内存块的一部分,因此它们的地址应该具有您想要的属性。
那这个呢:
int least;
least = (int)(&a) ^ (int)(&b); //this is a bitwise XOR, returning 0s when the bits are the same
if (least % 16) = 0 then
{
//first four bits are zeroes, meaning they all match
}
解决此问题的一种可能方法是使用分配函数,该函数将仅返回在 16 字节边界上对齐的分配(因此最低有效 4 位将始终为零)。
某些平台具有这种对齐保证分配功能,例如_aligned_malloc()
在 MSVC 或posix_memalign()
Unix 变体中。如果你没有这样的分配器可用,使用普通的香草返回对齐的内存块malloc()
是一个常见的面试问题——互联网搜索将为你提供许多可能的解决方案。