Compare commits

...

2 Commits

Author SHA1 Message Date
yassin-kammoun-sonarsource
4c2b560548 Update RSPEC 2025-03-26 14:08:49 +01:00
yassin-kammoun-sonarsource
3f7b8cf72d Create rule S7459 2025-03-26 12:50:06 +00:00
3 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,24 @@
{
"title": "`set_len` should not be called on uninitialized vectors",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7459",
"sqKey": "S7459",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,34 @@
== Why is this an issue?
In Rust, calling ``++Vec::set_len(new_len)++`` directly after allocating or reserving memory using ``++Vec::with_capacity()++``, ``++Vec::new()++``, ``++Vec::default()++``, or ``++Vec::reserve()++`` can lead to the creation of a ``++Vec++`` with uninitialized elements. This is problematic because most safe Rust operations assume initialized data. Using uninitialized data can result in undefined behavior, including memory corruption and unexpected program crashes.
This rule detects instances where ``++Vec::set_len()++`` is called directly after allocating or reserving memory with ``++Vec::with_capacity()++``, ``++Vec::new()++``, ``++Vec::default()++``, or ``++Vec::reserve()++``, without any prior initialization of the vector's elements. The rule performs a local analysis and only checks for these calls within adjacent statements.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
fn f(reader: &mut dyn std::io::Read) {
let mut vec: Vec<u8> = Vec::with_capacity(1000);
unsafe { vec.set_len(1000); } // Noncompliant: Uninitialized vector
reader.read_exact(&mut vec).unwrap(); // Undefined behavior!
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
fn f(reader: &mut dyn std::io::Read) {
let mut vec: Vec<u8> = vec![0; 1000]; // Properly initialized with zeros
reader.read_exact(&mut vec).unwrap(); // Safe to use
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#uninit_vec