#[0.15.2] Is this a use-after-return bug?

1 messages · Page 1 of 1 (latest)

bronze lion
#

Hello!

In my code, I am creating an empty array on the stack, passing it to a C function (which mutates it), and returning the result. Is this safe behaviour? I didn't get an error, and the code works as expected; however, I'm not sure if this is by design or a coincidence... thinkies I'm not familiar with the memory semantics here, so I'd appreciate if anyone could explain.

Here's an example of my use-case (c.populateArray is imported from C):

fn myFunc() [*c]const u8 {
    const size = 8;
    var arr: [size]u8 = .{0} ** size;
    c.populateArray(&arr, size);
    return &arr;
}

Thank you!

scarlet monolith
#

Yes that is a dangling pointer

bronze lion
#

ah, thanks for the fast response :-)

scarlet monolith
#

Also you should never use [*c]T in your own code

bronze lion
#

is it not required when inter-operating with C?

scarlet monolith
#

It's only necessary for auto-generated zig from translate-c because it doesn't know whether to use *T, [*]T, ?*T, or ?[*]T

#

In your own code you do know, so you should use one of those instead

bronze lion
scarlet monolith
#

Anywho, you can fix your code either by returning [8]u8, allocating, or having the user pass in the buffer

bronze lion
#

cool! that's what i figured. if i'm returning [8]u8, then a copy would be made, yes?

scarlet monolith
#

Semantically, yes. An optimization may occur of course

bronze lion
#

cool

#

i appreciate the help 🦝

true dragon
#

and its only a copy to the pointer and len part not the actual memory its being pointed to

scarlet monolith
bronze lion
#

this has me thinking... if i'm instead returning a slice type, is it still a use-after-return bug? 🤔

- fn myFunc() [*c]const u8 {
+ fn myFunc() [:0]const u8 {
scarlet monolith
#

Yes

#

A slice is still a pointer

bronze lion
#

so, is the Zig compiler suggesting that i should create a use-after-return bug in my code? 😕

src/main.zig:191:12: error: array literal requires address-of operator (&) to coerce to slice type '[:0]const u8'
    return arr;
#

please forgive my naïveté

scarlet monolith
#

Your function return type is [:0]const u8, so it's suggesting to you how to fix your type mismatch

#

In this case it ends up creating a uaf bug, yes

bronze lion
#

okay, thanks :-)

scarlet monolith