Implementing Memory-Safe Programming Practices to Prevent Vulnerabilities

Adopting memory-safe languages and techniques to reduce common security flaws in software development.

0 likes
15 views

Rule Content

---
description: "Enforce memory-safe programming practices to prevent vulnerabilities"
globs: ["**/*.c", "**/*.cpp", "**/*.h"]
tags: [security, memory-safety, best-practices]
priority: 1
version: 1.0.0
---

# Implementing Memory-Safe Programming Practices to Prevent Vulnerabilities

## Context
- Applies to all C and C++ source and header files.
- Aims to reduce common security flaws by enforcing memory-safe coding standards.

## Requirements
- **Avoid Unsafe Functions**: Do not use functions known for memory vulnerabilities, such as `gets`, `strcpy`, `strcat`, and `sprintf`. Instead, use safer alternatives like `fgets`, `strncpy`, `strncat`, and `snprintf`.
- **Implement Bounds Checking**: Always perform bounds checking when handling arrays and buffers to prevent buffer overflows.
- **Initialize Pointers and Variables**: Ensure all pointers and variables are initialized before use to avoid undefined behavior.
- **Use Smart Pointers**: Prefer smart pointers (`std::unique_ptr`, `std::shared_ptr`) over raw pointers to manage dynamic memory safely.
- **Explicitly Free Allocated Memory**: Properly deallocate dynamically allocated memory using `free` or appropriate deallocation functions to prevent memory leaks.
- **Enable Compiler Warnings**: Use compiler flags to enable warnings related to memory safety and address them promptly.
- **Conduct Static Analysis**: Regularly use static analysis tools to detect potential memory safety issues in the codebase.

## Examples

<example>
// Good: Using fgets instead of gets
char buffer[50];
fgets(buffer, sizeof(buffer), stdin);
</example>

<example type="invalid">
// Bad: Using gets, which is unsafe
char buffer[50];
gets(buffer);
</example>

<example>
// Good: Using std::unique_ptr for dynamic memory management
#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(10);
</example>

<example type="invalid">
// Bad: Using raw pointer without proper deallocation
int* ptr = new int(10);
// Potential memory leak if delete is not called
</example>