What is the output of this C code that uses defensive programming to prevent buffer overflow?
#include <stdio.h> #include <string.h> int main() { char buffer[10]; const char *input = "HelloWorld!"; if (strlen(input) < sizeof(buffer)) { strcpy(buffer, input); printf("Buffer content: %s\n", buffer); } else { printf("Input too large for buffer\n"); } return 0; }
Check the length of the input string compared to the buffer size.
The input string "HelloWorld!" has 11 characters plus the null terminator, which is too large for the 10-byte buffer. The code correctly detects this and prints the warning message.
Why is it important to check if a pointer is NULL before using it in C?
Think about what happens if you try to use a pointer that points to nothing.
Dereferencing a null pointer causes a runtime crash (segmentation fault). Checking for NULL prevents this by ensuring the pointer is valid before use.
What is the mistake in this code that tries to safely open a file?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { printf("File not found\n"); } fprintf(fp, "Hello\n"); fclose(fp); return 0; }
Look at what happens after the if (fp == NULL) check.
The code prints an error if the file failed to open but continues to write to the file pointer anyway, which is invalid and causes undefined behavior.
Which of the following code snippets will cause a compilation error due to defensive programming misuse?
Check the syntax of the if statement.
Option A is missing parentheses around the condition, which is required in C syntax for if statements.
What is the output of this C program that uses defensive programming to check for integer overflow before addition?
#include <stdio.h> #include <limits.h> int safe_add(int a, int b, int *result) { if ((b > 0) && (a > INT_MAX - b)) { return 0; // overflow } if ((b < 0) && (a < INT_MIN - b)) { return 0; // underflow } *result = a + b; return 1; // success } int main() { int x = INT_MAX; int y = 1; int res; if (safe_add(x, y, &res)) { printf("Sum: %d\n", res); } else { printf("Overflow detected\n"); } return 0; }
Consider what happens when adding 1 to INT_MAX.
The function detects that adding 1 to INT_MAX would overflow and returns 0, so the program prints "Overflow detected".