繁体   English   中英

如何在特定的 memory 地址中读取和写入 1 个字节?

[英]How to read & write 1 byte into a particular memory address?

我正在尝试从结构的特定 memory 地址读取单个字节,然后将相同的字节写入该相同的地址。 我的目标是将与该 memory 地址关联的 64 字节 memory 加载到缓存行中。

我有一个大小为12584的结构变量testStructure 我尝试使用以下代码将 1 个字节读回 memory 地址,

unsigned char *p;
int forEachCacheLine = sizeof(testStructure);
printf("size of forEachCacheLine is %d\n", forEachCacheLine);

for (int i = 0; i<forEachCacheLine ; i+=64) {

    printf("i is %d\n",i);

    // read 1 byte 
    p=(unsigned char *)&testStructure+i;
    printf("Read from %p byte is %hhx\n", &testStructure+i, p);


    // write 1 byte
    *(unsigned char *)(&testStructure+i)=p;
    printf("Write into %p byte is %hhx\n\n", &testStructure+i, p);
}

运行代码后,我得到以下 output:

size of forEachCacheLine is 12584
i is 0  
Read from 0x7f5d42e71f80 byte is 80
Write into 0x7f5d42e71f80 byte is 80

i is 64  
Read from 0x7f5d42f36980 byte is c0
Segmentation fault (core dumped)

如 output 所示,第一次迭代中的写入尝试成功。 但是,第二次迭代会导致Segfault 关于我为什么会出现此Segmentation fault的任何评论?

我不太确定这是否是实现我的目标的正确方法。 但到目前为止,这是我能想到的唯一方法。 如果这是一种不正确的方法,有人可以建议另一种方法吗?

虽然您的 for 循环似乎每次迭代仅将i增加 64 个字节,但您的调试 output 显示第二次读取比第一次读取多 805376 个字节 - 这超出了界限,可能导致段错误。 805376 是 12584 的 64 倍。这意味着每次迭代都将 p 增加 64 个teststructure而不是 64 个chars

尝试更换

p=(unsigned char *)&testStructure+i; 

p=((unsigned char *)&testStructure)+i;

这确保当我们将i添加到&teststructure teststructure* 时,它是一个char*而不是teststructure*

在大多数现代系统上,像这样显式缓存 memory 几乎没有性能提升。 如果你真的想要缓存中的 memory - 尝试在每 64 个字节的teststructure上使用__builtin_prefetch() 这是一个填充缓存行的 GNU 扩展。 您还应该注意它的可选 arguments。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM