Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

builtin: add &u8.free() #23598

Merged
merged 4 commits into from
Jan 28, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions vlib/builtin/array.v
Original file line number Diff line number Diff line change
@@ -1058,6 +1058,12 @@ pub fn (data &u8) vbytes(len int) []u8 {
return unsafe { voidptr(data).vbytes(len) }
}

// free frees the memory allocated
@[unsafe]
pub fn (data &u8) free() {
unsafe { free(data) }
}

@[if !no_bounds_checking ?; inline]
fn panic_on_negative_len(len int) {
if len < 0 {
4 changes: 2 additions & 2 deletions vlib/v/gen/c/autofree.v
Original file line number Diff line number Diff line change
@@ -205,7 +205,7 @@ fn (mut g Gen) autofree_var_call(free_fn_name string, v ast.Var) {
return
}
mut af := strings.new_builder(128)
if v.typ.is_ptr() {
if v.typ.is_ptr() && v.typ.idx() != ast.u8_type_idx {
af.write_string('\t')
if v.typ.share() == .shared_t {
af.write_string(free_fn_name.replace_each(['__shared__', '']))
@@ -241,7 +241,7 @@ fn (mut g Gen) autofree_var_call(free_fn_name string, v ast.Var) {
af.writeln('\tif (${c_name(v.name)}.state != 2) {')
af.writeln('\t\t${free_fn_name}((${base_type}*)${c_name(v.name)}.data); // autofreed option var ${g.cur_mod.name} ${g.is_builtin_mod}')
af.writeln('\t}')
} else {
} else if v.typ.idx() != ast.u8_type_idx {
af.writeln('\t${free_fn_name}(&${c_name(v.name)}); // autofreed var ${g.cur_mod.name} ${g.is_builtin_mod}')
}
}
11 changes: 11 additions & 0 deletions vlib/v/tests/u8_free_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fn test_main() {
unsafe {
mut data := malloc(4)
data[0] = c'f'
data[1] = c'o'
data[2] = c'o'
data[3] = c'\0'
assert data.vstring() == 'foo'
data.free()
}
}