Skip to content

No way to reset a large variant object without corrupting the stack #25438

@yglukhov

Description

@yglukhov

Nim Version

Nim Compiler Version 2.3.1 [Linux: amd64]
Compiled at 2026-01-14
Copyright (c) 2006-2026 by Andreas Rumpf

git hash: c1e381a
active boot switches: -d:release

Description

type
  Foo = object
    case isBig: bool
    of true:
      bigArray: array[100000000, byte]
    of false:
      discard

  Bar = ref object
    f: Foo

proc makeFooBig(f: var Foo, isBig: bool) =
  f = Foo(isBig: isBig) # How to change discriminant???

var b = Bar()
echo "Bar allocated"
makeFooBig(b.f, true) # Stack overflow
echo "OK"
nim c -r --passC="-flto -fstack-usage -Werror=stack-usage=524288" --passL="-flto -fstack-usage -Werror=stack-usage=524288" test.nim

C code for makeFooBig:

N_LIB_PRIVATE N_NIMCALL(void, makeFooBig__test7_u8)(tyObject_Foo__rTC9cDxGwsb1FuzDuHHpVrg* f_p0, NIM_BOOL isBig_p1) {
	NIM_BOOL colontmpD_;
	tyObject_Foo__rTC9cDxGwsb1FuzDuHHpVrg T1_; // STACK ALLOCATION!
	colontmpD_ = ((NIM_BOOL) 0);
	nimZeroMem(((void*) ((&T1_))), sizeof(tyObject_Foo__rTC9cDxGwsb1FuzDuHHpVrg));
	colontmpD_ = isBig_p1;
	T1_.isBig = colontmpD_;
	(*f_p0) = T1_;
}

Current Output

.../.cache/nim/test7_d/@mtest7.nim.c: In function ‘makeFooBig__test7_u8’:
.../.cache/nim/test7_d/@mtest7.nim.c:128:15: error: stack usage is 10000112 bytes [-Werror=stack-usage=]
  128 | N_LIB_PRIVATE N_NIMCALL(void, makeFooBig__test7_u8)(tyObject_Foo__rTC9cDxGwsb1FuzDuHHpVrg* f_p0, NIM_BOOL isBig_p1) {
      |               ^
lto1: some warnings being treated as errors
lto-wrapper: fatal error: gcc returned 1 exit status

Expected Output

Compile and run successfully

Known Workarounds

proc makeFooBig(f: var Foo, isBig: bool) =
  reset(f)
  {.push checks: off.}
  f.isBig = isBig
  {.pop.}

No response

Additional Information

Relevant issue: #25287

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions