内存对齐检查 [英] Memory alignment check

查看:148
本文介绍了内存对齐检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查分配的内存是否对齐.我正在使用_aligned_malloc(size, align);并且它返回一个指针.我可以通过简单地将指针内容除以16来检查它吗?如果指针的内容可以被16整除,是否意味着内存被16字节对齐?

I want to check whether an allocated memory is aligned or not. I am using _aligned_malloc(size, align); And it returns a pointer. Can I check it by simply dividing the pointer content by 16 for example? If the the pointer content is divisible by 16, does it mean that the memory is aligned by 16 bytes?

推荐答案

按定义,对齐"指针意味着该指针的数值可以被N整除(其中N是所需的对齐方式).要检查这一点,请将指针强制转换为适当大小的整数,取模数N,然后检查结果是否为零.在代码中:

An "aligned" pointer by definition means that the numeric value of the pointer is evenly divisible by N (where N is the desired alignment). To check this, cast the pointer to an integer of suitable size, take the modulus N, and check whether the result is zero. In code:

bool is_aligned(void *p, int N)
{
    return (int)p % N == 0;
}

如果要手动检查指针值,只需查看指针的十六进制表示,然后查看它是否以所需的0位数字结尾.例如,一个16字节对齐的指针值将始终以四个零位结尾.

If you want to check the pointer value by hand, just look at the hex representation of the pointer and see whether it ends with the required number of 0 bits. A 16 byte aligned pointer value will always end in four zero bits, for example.

这篇关于内存对齐检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆