How is this code invalid?

H. S. Teoh hsteoh at qfbox.info
Sat Dec 17 01:39:08 UTC 2022


On Sat, Dec 17, 2022 at 12:23:32AM +0000, thebluepandabear via Digitalmars-d-learn wrote:
[...]
> ```D
> int[] numbersForLaterUse;
> 
> void foo(int[] numbers...) {
>    numbersForLaterUse = numbers;
> }
> 
> struct S {
>   string[] namesForLaterUse;
> 
>   void foo(string[] names...) {
>      namesForLaterUse = names;
>   }
> }
> ```
[...]
> The thing is, when I run the code I get absolutely no error, so how is
> this exactly a 'bug' if the code runs properly? That's what I am
> confused about.  What is the D compiler doing behind the scenes?

Try labelling the above functions with @safe and see what the compiler
says.

If you really want to see what could possibly have gone wrong, try this
version of the code:

------------------------------snip-----------------------------------
int[] numbersForLaterUse;

void foo(int[] numbers...) {
   numbersForLaterUse = numbers;
}

struct S {
  string[] namesForLaterUse;

  void foo(string[] names...) {
     namesForLaterUse = names;
  }
}

void whatwentwrong() {
	import std.stdio;
	writeln(numbersForLaterUse);
}

void whatelsewentwrong(S s) {
	import std.stdio;
	writeln(s.namesForLaterUse);
}

void badCodeBad() {
  foo(1, 2, 3, 4, 5);
}

S alsoReallyBad() {
  S s;
  s.foo("hello", "world!");
  return s;
}

void main() {
  badCodeBad();
  whatwentwrong();

  auto s = alsoReallyBad();
  whatelsewentwrong(s);
}
------------------------------snip-----------------------------------

The results will likely differ depending on your OS and specific
environment; but on my Linux machine, it outputs a bunch of garbage
(instead of the expected numbers and "hello" "world!" strings) and
crashes.


T

-- 
If you want to solve a problem, you need to address its root cause, not just its symptoms. Otherwise it's like treating cancer with Tylenol...


More information about the Digitalmars-d-learn mailing list