Advertisement
pleasedontcode

Buffer Overflow Protection

Aug 26th, 2024
682
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 0.73 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. // Define buffer size
  5. #define BUFFER_SIZE 32
  6.  
  7. // Function to safely copy strings with buffer overflow protection
  8. void safeStringCopy(char *dest, const char *src, size_t size) {
  9.     if (strlen(src) >= size) {
  10.         printf("Error: Input string is too large!\n");
  11.         return;
  12.     }
  13.     strncpy(dest, src, size - 1);
  14.     dest[size - 1] = '\0';  // Ensure null termination
  15. }
  16.  
  17. int main() {
  18.     // Example buffer
  19.     char buffer[BUFFER_SIZE];
  20.  
  21.     // User input simulation
  22.     const char *userInput = "Hello, World!";
  23.  
  24.     // Perform safe string copy
  25.     safeStringCopy(buffer, userInput, BUFFER_SIZE);
  26.  
  27.     // Print the copied string
  28.     printf("%s\n", buffer);
  29.  
  30.     return 0;
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement