Skip to content

Commit 9ce2c51

Browse files
author
Felix Raimundo
committed
Document that CStrings live in the libc heap
Insists on the fact that the memory is managed by malloc and not jemalloc Closes #17067
1 parent 06e85fd commit 9ce2c51

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/librustrt/c_str.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ 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 libc's malloc and not
40+
by jemalloc which is the 'normal' rust memory allocator.
41+
That means that the CString pointers should only be freed with
42+
alloc::libc_heap::malloc_raw if you intend to do that on your own.
43+
3944
An example of creating and using a C string would be:
4045
4146
```rust
@@ -91,8 +96,8 @@ pub struct CString {
9196

9297
impl Clone for CString {
9398
/// 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.
99+
/// reasons, this is always a deep clone with the memory allocated
100+
/// with libc's malloc, rather than the usual shallow clone.
96101
fn clone(&self) -> CString {
97102
let len = self.len() + 1;
98103
let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
@@ -131,7 +136,8 @@ impl<S: hash::Writer> hash::Hash<S> for CString {
131136
}
132137

133138
impl CString {
134-
/// Create a C String from a pointer.
139+
/// Create a C String from a pointer, with memory managed by libc's malloc,
140+
/// so do not call it with a pointer allocated by jemalloc.
135141
///
136142
///# Failure
137143
///
@@ -265,7 +271,8 @@ impl CString {
265271
/// forgotten, meaning that the backing allocation of this
266272
/// `CString` is not automatically freed if it owns the
267273
/// allocation. In this case, a user of `.unwrap()` should ensure
268-
/// the allocation is freed, to avoid leaking memory.
274+
/// the allocation is freed, to avoid leaking memory. You have to
275+
/// use libc's memory allocator in this case.
269276
///
270277
/// Prefer `.as_ptr()` when just retrieving a pointer to the
271278
/// string data, as that does not relinquish ownership.

0 commit comments

Comments
 (0)