0
0
Cprogramming~10 mins

Defensive programming practices - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the pointer is NULL before using it.

C
if ([1] != NULL) {
    printf("Pointer is valid.\n");
}
Drag options to blanks, or click blank then click option'
Aptr
BNULL
C0
Dptr == NULL
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing NULL to NULL instead of the pointer variable.
Using 'ptr == NULL' inside the if condition which checks for non-null.
2fill in blank
medium

Complete the code to safely open a file and check if it opened successfully.

C
FILE *file = fopen("data.txt", "r");
if ([1] == NULL) {
    printf("Failed to open file.\n");
}
Drag options to blanks, or click blank then click option'
ANULL
Bfopen
Cfile
Ddata.txt
Attempts:
3 left
💡 Hint
Common Mistakes
Checking fopen directly instead of the file pointer variable.
Comparing the filename string to NULL.
3fill in blank
hard

Fix the error in the code to prevent buffer overflow by limiting input size.

C
char buffer[10];
printf("Enter text: ");
scanf("%[1]s", buffer);
Drag options to blanks, or click blank then click option'
A10
Bs
C99
D9
Attempts:
3 left
💡 Hint
Common Mistakes
Using %s without size limit causes buffer overflow.
Using %10s reads 10 characters but buffer can only hold 10 including null terminator.
4fill in blank
hard

Fill both blanks to safely allocate memory and check if allocation succeeded.

C
int *arr = (int *)malloc([1] * sizeof(int));
if (arr [2] NULL) {
    printf("Memory allocation failed.\n");
}
Drag options to blanks, or click blank then click option'
A10
B==
C!=
Dsizeof
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking if malloc returned NULL.
Using '!=' instead of '==' in the if condition.
5fill in blank
hard

Fill all three blanks to safely copy a string with length check.

C
char src[] = "Hello";
char dest[6];
if (strlen(src) [1] sizeof(dest) - 1) {
    strncpy(dest, src, [2]);
    dest[[3]] = '\0';
} else {
    printf("Source string too long.\n");
}
Drag options to blanks, or click blank then click option'
A<=
Bsizeof(dest) - 1
Cstrlen(src)
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding null terminator after strncpy.
Using wrong comparison operator causing buffer overflow.