Arrays and Strings
Bounded Copy
A bounded copy leaves room for the null terminator in the destination buffer.
Bounded Copy
bounded_copy.c
#include <stdio.h>
int main(void) {
char source[] = "trace";
char target[8];
int capacity = ;
int i = 0;
while (i < capacity - 1 && source[i] != '\0') {
target[i] = source[i];
i++;
}
target[i] = '\0';
printf("copy=%s\n", target);
return 0;
}
#include <stdio.h>
int main(void) {
char source[] = "trace";
char target[8];
int capacity = ;
int i = 0;
while (i < capacity - 1 && source[i] != '\0') {
target[i] = source[i];
i++;
}
target[i] = '\0';
printf("copy=%s\n", target);
return 0;
}
#include <stdio.h>
int main(void) {
char source[] = "trace";
char target[8];
int capacity = ;
int i = 0;
while (i < capacity - 1 && source[i] != '\0') {
target[i] = source[i];
i++;
}
target[i] = '\0';
printf("copy=%s\n", target);
return 0;
}
capacity
The destination capacity controls how many characters can be copied safely.
leave room
Copy at most `capacity - 1` characters, then write the terminator.