How does a 64-bit computer change one byte in memory?

Viewed 187

If a C program changes one byte in a byte array, what machine instructions take place? Does the hardware need read 8 bytes, change a byte, and store it (using 2 memory operations)?

Edit: Specifically on x86-64 architecture

2 Answers

On x86-64, the hardware will read one cache line, modify the byte in cache, and eventually that cache line will be written back to memory.

The main reason for the write-back to happen is that the CPU needs the cache line for other data. There are explicit instructions to force the write-back, but a C compiler would be unlikely to use those. It slows down the CPU to force an unnecessary write.

It all depends on the compiler, optimisations and etc. Just try to compile and to disassemble. As an example we will compile the following code:

#include <stdio.h>

int main() {
    char a[] = "01234567890";
    a[5] = 'A';
    printf("%s\n", a);
}

// gcc -o main -std=c11 -Wall -Wextra -O0 main.c 

We get the disassemby by objdump:

 6c1:   48 b8 30 31 32 33 34    movabs rax,0x3736353433323130
 6c8:   35 36 37 
 6cb:   48 89 45 ec             mov    QWORD PTR [rbp-0x14],rax
 6cf:   c7 45 f4 38 39 30 00    mov    DWORD PTR [rbp-0xc],0x303938
 6d6:   c6 45 f1 41             mov    BYTE PTR [rbp-0xf],0x41
 6da:   48 8d 45 ec             lea    rax,[rbp-0x14]
 6de:   48 89 c7                mov    rdi,rax

// objdump -d ./main -Mintel | less
Related