Skip to content

Nested array<array<T, N>, M> is an array of pointers, so it cannot be returned or stored safely #575

Closed

Description

@godofecht

Split out of #573, which fixed the single-level case.

What is wrong

A nested sized array is represented as an array of pointers throughout the C generator, not as T[M][N]. array<array<i32, 3>, 4> becomes int32_t*[4], and each pointer points at a local:

_flow_arr_int32_tp_4 progression_pop_i32(int32_t root) {
    int32_t I[3];  memcpy(I, chord_major_i32(root).v, sizeof(I));
    int32_t V[3];  ...
    return (int32_t*[]){ I, V, vi, IV };    // four pointers into this frame
}
warning: address of stack memory associated with compound literal {I, V, vi, IV} returned

Reading chords[0][0] after the call gives garbage or crashes.

Why #573's fix does not cover it

#573 wraps an array<T, N> return in struct { T v[N]; }, so the data is copied out by value. For a nested array that struct would be struct { int32_t* v[4]; }: four pointers, still into the dead frame. The wrapper only helps once the element storage is inline.

_sized_array_type therefore excludes nested arrays, leaving them on the old path. Behaviour is unchanged rather than half-changed.

What the fix needs

The representation has to become pointer-free before the return can be wrapped:

  • _c_type for a nested sized array emits int32_t (*)[3] or a full declarator rather than int32_t*
  • the local declaration at c_generator.py:2613 emits int32_t chords[4][3], not int32_t* chords[4]
  • the array literal for a nested array emits a brace-nested initializer, not (int32_t*[]){ ... }
  • only then does the struct { int32_t v[4][3]; } return wrapper work

Scope

Three functions in the repository return a nested sized array, all in lib/stdlib/audio/scales.flow: progression_145, progression_pop, progression_blues. Storing one in a local has the same defect, so the count of affected call sites is larger than the count of affected returns.

Repro

import "stdlib/audio/scales.flow"

function main() -> i32 {
    let chords: array<array<i32, 3>, 4> = progression_pop(note_C(4))
    printf("first chord: %d %d %d\n", chords[0][0], chords[0][1], chords[0][2])
    return 0
}

Expected 48 52 55. Actual: garbage, or a trap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions