D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4791 - Assigning a static array to itself should be allowed
Summary: Assigning a static array to itself should be allowed
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords: pull, rejects-valid
Depends on:
Blocks:
 
Reported: 2010-09-02 21:48 UTC by David Simcha
Modified: 2018-04-25 05:40 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description David Simcha 2010-09-02 21:48:58 UTC
void main() {
    int[2] foo;
    foo = foo;
}

object.Exception: overlapping array copy

This is a ridiculous limitation and is bugs waiting to happen.  (For example, Bug 4789.)  Even if this requires a simple runtime check before calling memcpy() or whatever, IMHO it's worth it because the cost of a single pointer comparison is negligible in almost all cases and for tiny static arrays (where it might not be negligible) the compiler could just generate regular assignment instructions that are safe for the overlapping/identical case instead of using something like memcpy().
Comment 1 bearophile_hugs 2010-09-03 04:39:48 UTC
The only correct syntax to write that code is this, see bug 3971

void main() {
    int[2] foo;
    foo[] = foo[];
}
Comment 2 David Simcha 2010-09-03 05:25:43 UTC
Yes, and this is a nightmare for generic code.
Comment 3 Kenji Hara 2014-06-06 06:50:16 UTC
The root issue is a dup of bug 12212, and it's properly fixed in 2.066 git-head.

I'll add a case to the dmd test suite to avoid regressions.
https://github.com/D-Programming-Language/dmd/pull/3628
Comment 4 github-bugzilla 2014-06-06 07:30:27 UTC
Commits pushed to master at https://github.com/D-Programming-Language/dmd

https://github.com/D-Programming-Language/dmd/commit/4157e764c620984376da81d67eb83e67fb725d6e
fix Issue 4791 - Assigning a static array to itself should be allowed

https://github.com/D-Programming-Language/dmd/commit/d2347f6265a63fc15a4c478f109b32b0eb67ad1b
Merge pull request #3628 from 9rnsr/fix4791

Issue 4791 - Assigning a static array to itself should be allowed
Comment 5 bearophile_hugs 2014-06-06 07:40:34 UTC
(In reply to David Simcha from comment #2)
> Yes, and this is a nightmare for generic code.

A recent bug in my code (I have used a loop to avoid the overhead of calling the runtime function):


void main() {
    int[3] a, b, c;
    foreach (immutable i; 0 .. a.length)
        c = a[i] + b[i];
}


The correct foreach body is instead:

c[i] = a[i] + b[i];


So I think there are disadvantages at not requiring a [] syntax for all array-wide operations.