@@ -36,6 +36,12 @@ not tied to the lifetime of the original string/data buffer). If C strings are
36
36
heavily used in applications, then caching may be advisable to prevent
37
37
unnecessary amounts of allocations.
38
38
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
+
39
45
An example of creating and using a C string would be:
40
46
41
47
```rust
@@ -91,8 +97,8 @@ pub struct CString {
91
97
92
98
impl Clone for CString {
93
99
/// 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.
96
102
fn clone ( & self ) -> CString {
97
103
let len = self . len ( ) + 1 ;
98
104
let buf = unsafe { malloc_raw ( len) } as * mut libc:: c_char ;
@@ -131,7 +137,9 @@ impl<S: hash::Writer> hash::Hash<S> for CString {
131
137
}
132
138
133
139
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.
135
143
///
136
144
///# Failure
137
145
///
@@ -265,7 +273,8 @@ impl CString {
265
273
/// forgotten, meaning that the backing allocation of this
266
274
/// `CString` is not automatically freed if it owns the
267
275
/// 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.
269
278
///
270
279
/// Prefer `.as_ptr()` when just retrieving a pointer to the
271
280
/// string data, as that does not relinquish ownership.
0 commit comments