Buffer overflows in C often occur when a program writes more data to a buffer, such as an array or a block of allocated memory, than it can hold.
Buffer overflows in C can be mitigated by avoiding unsafe functions and using their safer counterparts, such as the examples shown in the table below. This helps ensure that buffer limits are respected and reduces the risk of overflow.
Unsafe Function | Safer Counterpart |
---|---|
strcpy() |
strncpy() |
strcat() |
strncat() |
gets() |
fgets() |
sprintf() |
snprintf() |
After-free in C often occurs when a program continues to use a pointer after the memory it points to has been freed.
After-free in C can be mitigated by setting pointers to NULL
immediately after freeing the associated memory to avoid dangling pointers.
Memory leaks in C often occur when a program allocates memory dynamically but fails to release it back to the system when it is no longer needed.
Memory leaks in C can be mitigated by ensuring that dynamically allocated memory is paired with an appropriate free()
call.
Format string vulnerabilities in C often occur when a program uses user input directly in the format string parameter of the string formatting function.
#include <stdio.h>int main() {char userInput[100];printf("Enter a string: ");fgets(userInput, sizeof(userInput), stdin);// Vulnerable code: using user input directly in the format stringprintf(userInput);return 0;}
Format string vulnerabilities in C can be mitigated by refraining from using user-controlled input as the format string in printf
-style functions.
Integer overflows in C often occur because the C programming language does not automatically check for overflow (when a value exceeds the maximum limit) or underflow (when a value goes below the minimum limit) conditions during arithmetic operations.
Integer overflows in C can be mitigated by carefully checking and validating all inputs and using safe arithmetic functions that detect and handle overflows and underflows.