Skip to content

Commit a116c72

Browse files
committed
rollup merge of #17355 : gamazeps/issue17210
2 parents dbaa930 + 50d179d commit a116c72

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/librustrt/c_str.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ not tied to the lifetime of the original string/data buffer). If C strings are
3636
heavily used in applications, then caching may be advisable to prevent
3737
unnecessary amounts of allocations.
3838
39+
Be carefull to remember that the memory is managed by C allocator API and not
40+
by Rust allocator API.
41+
That means that the CString pointers should be freed with C allocator API
42+
if you intend to do that on your own, as the behaviour if you free them with
43+
Rust's allocator API is not well defined
44+
3945
An example of creating and using a C string would be:
4046
4147
```rust
@@ -91,8 +97,8 @@ pub struct CString {
9197

9298
impl Clone for CString {
9399
/// Clone this CString into a new, uniquely owned CString. For safety
94-
/// reasons, this is always a deep clone, rather than the usual shallow
95-
/// clone.
100+
/// reasons, this is always a deep clone with the memory allocated
101+
/// with C's allocator API, rather than the usual shallow clone.
96102
fn clone(&self) -> CString {
97103
let len = self.len() + 1;
98104
let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
@@ -131,7 +137,9 @@ impl<S: hash::Writer> hash::Hash<S> for CString {
131137
}
132138

133139
impl CString {
134-
/// Create a C String from a pointer.
140+
/// Create a C String from a pointer, with memory managed by C's allocator
141+
/// API, so avoid calling it with a pointer to memory managed by Rust's
142+
/// allocator API, as the behaviour would not be well defined.
135143
///
136144
///# Failure
137145
///
@@ -265,7 +273,8 @@ impl CString {
265273
/// forgotten, meaning that the backing allocation of this
266274
/// `CString` is not automatically freed if it owns the
267275
/// allocation. In this case, a user of `.unwrap()` should ensure
268-
/// the allocation is freed, to avoid leaking memory.
276+
/// the allocation is freed, to avoid leaking memory. You should
277+
/// use libc's memory allocator in this case.
269278
///
270279
/// Prefer `.as_ptr()` when just retrieving a pointer to the
271280
/// string data, as that does not relinquish ownership.

0 commit comments

Comments
 (0)