Function libyml::memory::yaml_strdup

source ·
pub unsafe fn yaml_strdup(str: *const u8) -> *mut u8
Expand description

Duplicate a string using the system’s malloc function and manual copy due to type mismatch.

This function creates a new copy of the input string, allocating new memory for it.

§Arguments

  • str - A pointer to the null-terminated string to duplicate.

§Returns

Returns a pointer to the newly allocated string, or a null pointer if the allocation failed or the input was null.

§Safety

This function is unsafe because:

  • It involves memory allocation and raw pointer manipulation.
  • The caller must ensure that str is a valid, null-terminated string.
  • The caller is responsible for freeing the returned pointer using yaml_free.

§Examples

use libyml::memory::{yaml_strdup, yaml_free};
use libyml::yaml::yaml_char_t;
use core::ffi::c_void;

unsafe {
    // Note: The cast to *const yaml_char_t is necessary because yaml_char_t
    // might not be the same as u8 on all systems.
    let original: *const yaml_char_t = b"Hello, world!\0".as_ptr() as *const yaml_char_t;
    let copy = yaml_strdup(original);
    if !copy.is_null() {
        // Use the duplicated string
        // ...
        yaml_free(copy as *mut c_void);
    }
}