www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Crash in struct opAssign

reply olivier <h h.invalid> writes:
Hi,

This program, compiled with dmd 1.065 under Linux, crashes:

void main() {
	Num a = 1;
}

struct Num {
	int[] d;

	Num opAssign( int v ) {
		d.length = 1;
		d[0] = v;
		return *this;
	}
}

It looks like d is not initialized before opAssign() is called.
It doesn't crash if I replace "Num a = 1" with:
Num a;
a = 1;

Is this normal behaviour?
Dec 02 2010
parent reply Adam Burton <adz21c gmail.com> writes:
olivier wrote:

 Hi,
 
 This program, compiled with dmd 1.065 under Linux, crashes:
 
 void main() {
 Num a = 1;
 }
 
 struct Num {
 int[] d;
 
 Num opAssign( int v ) {
 d.length = 1;
 d[0] = v;
 return *this;
 }
 }
 
 It looks like d is not initialized before opAssign() is called.
 It doesn't crash if I replace "Num a = 1" with:
 Num a;
 a = 1;
 
 Is this normal behaviour?
I don't believe the failing code uses opAssign. I believe that is initialization. In D2 "Num a = 1;" would be initialization or call a constructor if appropriate and "Num a; a = 1;" would use opAssign. Based on http://www.digitalmars.com/d/1.0/struct.html I am thinking it does the same (minus the constructors). So I think this might be a bug with struct initialization in D1, I don't think you should be able to just assign 1 to it.
Dec 02 2010
next sibling parent Don <nospam nospam.com> writes:
Adam Burton wrote:
 olivier wrote:
 
 Hi,

 This program, compiled with dmd 1.065 under Linux, crashes:

 void main() {
 Num a = 1;
 }

 struct Num {
 int[] d;

 Num opAssign( int v ) {
 d.length = 1;
 d[0] = v;
 return *this;
 }
 }

 It looks like d is not initialized before opAssign() is called.
 It doesn't crash if I replace "Num a = 1" with:
 Num a;
 a = 1;

 Is this normal behaviour?
I don't believe the failing code uses opAssign. I believe that is initialization. In D2 "Num a = 1;" would be initialization or call a constructor if appropriate and "Num a; a = 1;" would use opAssign. Based on http://www.digitalmars.com/d/1.0/struct.html I am thinking it does the same (minus the constructors). So I think this might be a bug with struct initialization in D1, I don't think you should be able to just assign 1 to it.
My guess is that it's doing: a.d[] = 1; and since d.length==0, that's a no-op. It shouldn't compile.
Dec 02 2010
prev sibling parent olivier <h h.invalid> writes:
On Thu, 02 Dec 2010 17:32:41 +0000, Adam Burton wrote:

 I don't believe the failing code uses opAssign.
Yes, opAssign() is called. I can easily see that by adding a writefln() in it. I guess I should file a bug report...
Dec 03 2010