Among the most elegant implementations is the string copy function (assuming you have allocated enough memory in the dest buffer):
//Assuming for elegance you don't have to return the number of bytes copied.
void strcpy(char* src, char* dest){
while(*dest++ = *src++);
}
But I have often wondered what happens at the assembler such *s
gets you only a single byte/character. So here is a simple program that explores this - but in string compare:
int main(){
char *a="String One", *b="String Two";
while(*a++==*b++);
return 0;
}
I compiled this with ‘gcc -S’ option and got the following assembly code:
1 .file "testpointer.c"
2 .def ___main; .scl 2; .type 32; .endef
3 .section .rdata,"dr"
4LC0:
5 .ascii "a\0"
6LC1:
7 .ascii "b\0"
8 .text
9.globl _main
10 .def _main; .scl 2; .type 32; .endef
11_main:
12 pushl %ebp
13 movl %esp, %ebp
14 andl $-16, %esp
15 subl $16, %esp
16 call ___main
17 movl $LC0, 8(%esp)
18 movl $LC1, 12(%esp)
19L2:
20 movl 8(%esp), %eax
21 movb (%eax), %dl
22 movl 12(%esp), %eax
23 movb (%eax), %al
24 cmpb %al, %dl
25 sete %al
26 incl 8(%esp)
27 incl 12(%esp)
28 testb %al, %al
29 jne L2
30 movl $0, %eax
31 leave
32 ret
Line 24: cmpb %al, %dl
says it all. compare Lower Byte of register a
and register d
. Now I can be in peace ;)