Skip to content

Commit f467a98

Browse files
Copilotnunoplopes
andauthored
Initialize empty std::string values with a null terminator (#478)
The `std::string` rules model strings as null-terminated vectors, but default initialization produced an empty vector. Operations such as `length()` then incorrectly assume a terminator exists. - **Type rules:** Initialize default strings with `vec![0]` in both unsafe and refcount models. - **Regression coverage:** Add a default-constructed string case that checks `length()`. ```cpp std::string empty; assert(empty.length() == 0); ``` <!-- START COPILOT CODING AGENT SUFFIX --> - Fixes #455 --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Nuno Lopes <nuno.lopes@tecnico.ulisboa.pt>
1 parent 70c3401 commit f467a98

5 files changed

Lines changed: 8 additions & 2 deletions

File tree

‎rules/string/tgt_refcount.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::cell::RefCell;
66
use std::rc::Rc;
77

88
fn t1() -> Vec<i8> {
9-
Vec::new()
9+
vec![0]
1010
}
1111

1212
fn t2() -> Ptr<i8> {

‎rules/string/tgt_unsafe.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Distributed under the MIT license that can be found in the LICENSE file.
33

44
fn t1() -> Vec<libc::c_char> {
5-
Vec::new()
5+
vec![0]
66
}
77

88
fn t2() -> *mut libc::c_char {

‎tests/unit/out/refcount/string.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ pub fn main() {
1111
std::process::exit(main_0());
1212
}
1313
fn main_0() -> i32 {
14+
let mut empty: Vec<i8> = vec![0];
15+
assert!(((empty.len() - 1) == 0_usize));
1416
let s1: Value<Vec<i8>> = Rc::new(RefCell::new({
1517
let mut __bytes = Ptr::<i8>::from_string_literal(b"hello").to_c_bytes();
1618
__bytes.push(0);

‎tests/unit/out/unsafe/string.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ pub fn main() {
1313
}
1414
}
1515
unsafe fn main_0() -> i32 {
16+
let mut empty: Vec<libc::c_char> = vec![0];
17+
assert!(((empty.len() - 1) == (0_usize)));
1618
let mut s1: Vec<libc::c_char> = {
1719
let s = c"hello".as_ptr();
1820
std::slice::from_raw_parts(s, (0..).take_while(|&i| *s.add(i) != 0).count() + 1).to_vec()

‎tests/unit/string.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#include <string>
44

55
int main() {
6+
std::string empty;
7+
assert(empty.length() == 0);
68
std::string s1 = "hello";
79
assert(s1.length() == 5);
810
assert(s1.size() == s1.length());

0 commit comments

Comments
 (0)