Memory safe in D
Walter Bright
newshound2 at digitalmars.com
Mon Mar 18 22:36:21 UTC 2024
On 3/13/2024 9:06 AM, Petar Kirov [ZombineDev] wrote:
> Here's how TypeScript deals with this problem:
>
> ```ts
> class A { bar() {} }
>
> function foo(i: number) {
> let a: A;
> if (i) a = new A();
>
> if (i) a.bar(); // Error: Variable 'a' is used before being assigned.
> }
>
> function foo2(i: number) {
> let a: A | null = null;
> if (i) a = new A();
>
> if (i) a.bar(); // Error: 'a' is possibly 'null'
> }
>
> ```
Yes, that is one way to do it, disallowing otherwise valid programs. I ran into
this with C, and there was too much C code that would be disallowed, so I didn't
proceed with it.
Another issue with this approach is as soon as you pass `a` to another function,
`bar(a)`, the body of `bar` doesn't know if `a` is null or not.
So this kind of analysis is not generally useful.
The same thing comes up with:
```
int* foo() { int a; return &a; }
```
Most every C compiler will detect that. But there are many ways to slip it past
the compiler:
```
int* foo() { int a; int* p = &a; return bar(p); }
int* bar(int* p) { return p; }
```
which is why D came up with `scope` and `return`.
More information about the Digitalmars-d
mailing list