Skip to content

stage2 self referential array memory corruption #13415

@scheibo

Description

@scheibo

Zig Version

0.11.0-dev.18+81c27677d

Steps to Reproduce and Observed Behavior

const std = @import("std");

var i: u8 = 3;

fn bar(a: u8, b: u8, c: []u8) u8 {
    var j: u8 = 0;
    while (j < b) : (j += 1) {
        c[j] = a + j;
    }
    return a;
}

pub fn main() !void {
    var foo: [10]u8 = undefined;
    const baz = foo[bar(i, 6, &foo)];
    const qux = foo[bar(i, 9, &foo)];
    std.debug.print("{d} {d}\n", .{ baz, qux });

	 // workaround - behaves as expected
    var arr: [10]u8 = undefined;
    const a = bar(i, 6, &arr);
    const b = arr[a];
    const c = bar(i, 9, &arr);
    const d = arr[c];
    std.debug.print("{d} {d}\n", .{ b, d });
}
$ zig run main.zig
170 6
6 6

possibly eagerly reading from undefined memory?

Expected Behavior

This worked with stage 1:

$ zig run -fstage1 main.zig
6 6
6 6

and alternatively works in C:

#include <stdio.h>

int bar(int a, int b, int c[10]) {
  for (int j = 0; j < b; j++) {
    c[j] = a + j;
  }
  return a;
}

int main() {
  int i = 3;

  int foo[10];
  int baz = foo[bar(i, 6, &foo)];
  int qux = foo[bar(i, 9, &foo)];
  printf("%d %d\n", baz, qux);

  int arr[10];
  int a = bar(i, 6, &arr);
  int b = arr[a];
  int c = bar(i, 9, &arr);
  int d = arr[c];
  printf("%d %d\n", b, d);

  return 0;
}
$ zig  cc main.c && ./a.out
6 6
6 6

Metadata

Metadata

Assignees

No one assigned

    Labels

    frontendTokenization, parsing, AstGen, Sema, and Liveness.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions