Skip to content

Incorrect flexible array member C translation #211

@dacsson

Description

@dacsson

Zig Version

0.16.0-dev.747+493ad58ff

Steps to Reproduce and Observed Behavior

This C struct with flexible array member:

typedef struct {
  int    object_header;    
  void*  object_fields[0];  
} m_object;

Gets translated to:

pub const m_object = extern struct {
    object_header: c_int = 0,
    _object_fields: [0]?*anyopaque = @import("std").mem.zeroes([0]?*anyopaque),
    pub fn object_fields(self: anytype) __helpers.FlexibleArrayType(@TypeOf(self), @typeInfo(@TypeOf(self.*._object_fields)).array.child) {
        return @ptrCast(&self.*._object_fields);
    }
};

Which in turn, when trying to call it like this:

const fields = obj.object_fields();

Fails with:

.zig-cache/o/f9246e760d2eb128826c0b863b897370/cimport.zig:564:16: error: @ptrCast increases pointer alignment
        return @ptrCast(&self.*._object_fields);
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.zig-cache/o/f9246e760d2eb128826c0b863b897370/cimport.zig:564:25: note: '*align(1) [0]?*anyopaque' has alignment '1'
        return @ptrCast(&self.*._object_fields);
                        ^~~~~~~~~~~~~~~~~~~~~~
.zig-cache/o/f9246e760d2eb128826c0b863b897370/cimport.zig:564:16: note: '[*c]?*anyopaque' has alignment '8'
.zig-cache/o/f9246e760d2eb128826c0b863b897370/cimport.zig:564:16: note: use @alignCast to assert pointer alignment

Struct comes from runtime.h which is @cImport and link with runtime.c: library.root_module.addCSourceFile(.{ .file = b.path("runtime.c") });

Expected Behavior

Probably expected:

pub const m_object = extern struct {
    object_header: c_int = 0,
    _object_fields: [0]?*anyopaque = @import("std").mem.zeroes([0]?*anyopaque),
    pub fn object_fields(self: anytype) __helpers.FlexibleArrayType(@TypeOf(self), @typeInfo(@TypeOf(self.*._object_fields)).array.child) {
        return @ptrCast(&self.*._object_fields);
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions