Always verify that pointers and function return values are not null before dereferencing or using them. This prevents crashes and undefined behavior, especially when working with C functions or manual memory management.
Always verify that pointers and function return values are not null before dereferencing or using them. This prevents crashes and undefined behavior, especially when working with C functions or manual memory management.
Key practices:
display := C.XOpenDisplay(0)
should be followed by a null check since XOpenDisplay is documented to return null on failureassert green_arena.data != unsafe { nil }
and assert green_arena.head != unsafe { nil }
if g.fn_decl == unsafe { nil } || g.fn_decl.return_type == ast.void_type
prevents crashes when fn_decl might be uninitializedcurrent.next = unsafe { nil }
after free(current)
Example from discussions:
// Bad: No null check for C function return
display := C.XOpenDisplay(0)
// Immediate use without verification
// Good: Check for null return
display := C.XOpenDisplay(0)
if display == unsafe { nil } {
return error('Failed to open display')
}
defer { C.XCloseDisplay(display) }
This practice is essential for robust code that interfaces with C libraries or manages pointers manually.
Enter the URL of a public GitHub repository