why does it work on windowsXP, but not on linux?

closed account (iw0XoG1T)
on line 59 I pass strdup as a reference, but when I wrote this and compiled it originally on window I did not pass it as a reference. On widows there was no problem (that I was aware of,) but when I compiled it on linux I got this message when I ran it:
*** glibc detected *** ./strdup: double free or corruption (fasttop): 0x09f64008 ***

After I change line 59 to strdup& it ran without issue--any idea why?
here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include<iostream>
#include<stdexcept>

using namespace std;

//=============================================================================

struct Strdup{

	Strdup(){

		sz=0;

		copy =new char[sz];

		*copy=0;

	}

	Strdup(const char* t){

		str_count(t);

		copy=new char[sz+1];

		for(unsigned i =0; i<sz;i++){*(copy+i)=*(t+i);}
	}

	void str_count(const char* t){

		sz=0;

		while(*t){++sz;++t;}

	}

	

	~Strdup(){delete[] copy;}

	

	char* get(){return copy;}

	int size()const{return sz;}

	

	private:

		char* copy;

		unsigned sz;

};

//=============================================================================

ostream& operator<<(ostream& os, Strdup& s){

	return os<<s.get();

}

//=============================================================================

int main()try{

	

	Strdup test="this";

	cout<<test<<' '<<test.size()<<endl;

	

	return 0;

}

catch(exception& e){
	cerr<<e.what()<<endl;

	return 1;

}

catch(...){

	return 2;

}
Line 16 should produce a segmentation fault, since you're creating an array of size 0 (which is something you should never do, by the way) and assigning a zero to its first element, which doesn't exist.
What is seg fault really? You should write an article Helios.
closed account (iw0XoG1T)
Thank you--I will correct line 16.
Topic archived. No new replies allowed.