Destination = "Hello" Source = "World" Buffer size = 11
HelloWorld
#include <stdio.h>
void safe_append(char dest[], int destSize, const char src[]) {
int i = 0, j = 0;
// Find length of destination
while (dest[i] != '�') {
i++;
}
// Find length of source
while (src[j] != '�') {
j++;
}
// Check for buffer overflow
if (i + j + 1 > destSize) {
printf("Error: Buffer overflow prevented. Append not allowed.n");
return;
}
// Append source to destination
j = 0;
while (src[j] != '�') {
dest[i] = src[j];
i++;
j++;
}
dest[i] = '�'; // null terminate
}
int main() {
char destination[20] = "Hello";
char source[] = " World";
safe_append(destination, sizeof(destination), source);
printf("Resulting string: %sn", destination);
return 0;
}
#include <stdio.h>
void safe_append(char dest[], int destSize, const char src[]) {
int i = 0, j = 0;
// Find length of destination
while (dest[i] != '�') {
i++;
}
// Find length of source
while (src[j] != '�') {
j++;
}
// Check for buffer overflow
if (i + j + 1 > destSize) {
printf("Error: Buffer overflow prevented. Append not allowed.n");
return;
}
// Append source to destination
j = 0;
while (src[j] != '�') {
dest[i] = src[j];
i++;
j++;
}
dest[i] = '�'; // null terminate
}
int main() {
char destination[20] = "Hello";
char source[] = " World";
safe_append(destination, sizeof(destination), source);
printf("Resulting string: %sn", destination);
return 0;
}