I'm trying to read a single byte from a particular memory address of a structure followed by writing that same byte into that same address. My goal is to load 64-byte memory associated with that memory address into the cache line.
I have a structure variable testStructure
of size 12584
. I tried the following code to read and write back 1 byte into the memory address,
unsigned char *p;
int forEachCacheLine = sizeof(testStructure);
printf("size of forEachCacheLine is %d
", forEachCacheLine);
for (int i = 0; i<forEachCacheLine ; i+=64) {
printf("i is %d
",i);
// read 1 byte
p=(unsigned char *)&testStructure+i;
printf("Read from %p byte is %hhx
", &testStructure+i, p);
// write 1 byte
*(unsigned char *)(&testStructure+i)=p;
printf("Write into %p byte is %hhx
", &testStructure+i, p);
}
upon running the code I get the following 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)
As the output shows, the writing attempt in the first iteration was successful. However, the second iteration causes a Segfault
. Any comments on why I'm getting this Segmentation fault
?
I'm not quite sure if this is the correct approach to achieve my goal. But as of now, this is the only way I can think off. If this is an incorrect approach can someone please suggest an alternate approach?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…