Codecademy Logo

Secure Coding Practices in C

Buffer Overflows in C

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. 

An image showing a buffer overflow. There are two arrays of random 2-digit hexadecimal values, and the first four indexes are labeled “buffer”. In the second array, the second half of the array is labeled with "overflow", and it's clear someone has filled the second half of the array with strange data: the word “dead beef” is repeated twice.

Mitigating Buffer Overflows in C

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()

Use After Free in C

After-free in C often occurs when a program continues to use a pointer after the memory it points to has been freed. 

Mitigating Use After Free in C

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

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. 

Mitigating Memory Leaks in C

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

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 string
printf(userInput);
return 0;
}

Mitigating Format String Vulnerabilities in C

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

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.

Mitigating Integer Overflows in C

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.

Learn more on Codecademy