How do I pass a `CPointer` that points to the end ...
# kotlin-native
n
How do I pass a
CPointer
that points to the end of a
CArrayPointer
as a parameter to a C function? Below is what I have so far:
Copy code
private val globalArena = Arena()
// Use 65 KB for the stack size.
private const val STACK_SIZE = 65536
private val stack = globalArena.allocArray<ByteVar>(STACK_SIZE)
// ...

fun main() {
    println("Hello from Parent!")
    clone_process(fn = staticCFunction(::runContainer), stack = stack + STACK_SIZE, flags = SIGCHLD, arg = null)
    // ...
}
// ...
Running the program results in a segmentation fault occurring after calling the clone_process function.
@Alexey Belkov [JB] - Is there a function which returns a
CPointer
that points to the end of a
CArrayPointer
?
d
Pointer arithmetic should work
l
Wouldn't you need to pass in stack + STACK_SIZE - 1 to point to the last element? In the case of size = 1, the start and end are the same so the end is stack + 1 - 1, or just stack. You can extrapolate from there. I believe your code points to the byte after the last element, which is outside of explicitly allocated memory. This is undefined behaviour in C
CArrayPointer is just a helpful alias of CPointer, so it doesn't save the size itself. You have to keep track of it.
n
How do I apply pointer arithmetic to a
CArrayPointer
?
l
It's a typealias, so it should be the same. I'm not at a compiler right now, though.
d
You'll have to cast reinterpret it to a sized pointer like
CPointer<ByteVar>
n
Looks like the following works without ending up with a seg fault:
Copy code
clone_process(
        fn = staticCFunction(::runContainer),
        stack = stack + (STACK_SIZE - 1),
        flags = SIGCHLD,
        arg = null
    )
With this line
stack + (STACK_SIZE - 1)
the type is
CArrayPointer<ByteVar>
, which is the same type stack uses. Below is the output from the program:
Copy code
Hello from Parent!
Hello from Child!
🎉 1
Very interesting with Kotlin (via Kotlin Native) that nearly the same thing can be done like C. With C it would look like this:
stack + STACK_SIZE
l
Wouldn't that still reference the byte after the last? I can imagine C not catching the memory error, but it should still be undefined.
n
Kotlin handles array bounds differently from C, especially with array pointers.