In past I’ve asked something like (a more principled variant of) C Variable Length Arrays for Rust, but lately they are removing them all from Linux kernel, so I am not sure it’s a good idea to add them to Rust:
But the slide 8 is suspicious, to me it seems too much added code. So I’ve tried the code myself:
#include <stdio.h>
#include <string.h>
void call_me1(char *stuff, int step) {
char buf[10];
strncpy(buf, stuff, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
printf("%d:[%s]\n", step, buf);
}
void call_me2(char *stuff, int step) {
char buf[step];
strncpy(buf, stuff, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
printf("%d:[%s]\n", step, buf);
}
The asm shows a smaller difference:
.LC0:
.string "%d:[%s]\n"
call_me1(char*, int):
push rbx
mov edx, 9
mov ebx, esi
sub rsp, 16
mov rsi, rdi
lea rdi, [rsp+6]
call strncpy
lea rdx, [rsp+6]
mov esi, ebx
mov edi, OFFSET FLAT:.LC0
xor eax, eax
mov BYTE PTR [rsp+15], 0
call printf
add rsp, 16
pop rbx
ret
call_me2(char*, int):
push rbp
mov rbp, rsp
push r12
push rbx
movsx rbx, esi
lea rax, [rbx+15]
and rax, -16
sub rsp, rax
lea rdx, [rbx-1]
mov rsi, rdi
mov rdi, rsp
call strncpy
mov rdx, rsp
mov esi, ebx
mov edi, OFFSET FLAT:.LC0
xor eax, eax
mov BYTE PTR [rsp-1+rbx], 0
call printf
lea rsp, [rbp-16]
pop rbx
pop r12
pop rbp
ret