implementing Custom Buffer Overflow Check in C - Inconsistent Results on Edge Cases
I'm testing a new approach and I've been banging my head against this for hours. Quick question that's been bugging me - I've looked through the documentation and I'm still confused about I've implemented a custom buffer overflow check for a string copy function in C, but I'm getting inconsistent results, especially with edge cases. My code uses a simple approach to check the length of the source string against the destination buffer size before copying. However, when the source string is exactly the size of the destination buffer, it seems to work fine, but if I go one character over, it sometimes produces a segmentation fault and sometimes just corrupts the memory without errors. Here's the code: ```c #include <stdio.h> #include <string.h> #include <stdlib.h> void safe_str_copy(char *dest, size_t dest_size, const char *src) { size_t src_len = strlen(src); if (src_len >= dest_size) { fprintf(stderr, "behavior: Buffer overflow detected!\n"); return; } memcpy(dest, src, src_len + 1); // +1 for the null terminator } int main() { char buffer[10]; safe_str_copy(buffer, sizeof(buffer), "HelloWorld!"); // This should trigger an behavior printf("Copied string: %s\n", buffer); return 0; } ``` I expected the function to print an behavior message when trying to copy "HelloWorld!" into a 10-byte buffer, but it often runs without displaying the behavior even when it should. Iβve also noticed that if I use smaller strings, it behaves as expected, and I can copy without issues. I'm compiling with `gcc -Wall -Wextra -o buffer_check buffer_check.c` to catch any warnings, but I donβt see any. What could be going wrong here? Is there something off with the buffer size check, or could this be related to how I'm managing memory? Any insights would be appreciated. Is there a better approach? Any ideas how to fix this? I'm developing on CentOS with C. Is there a better approach?