unable to understand why there's a leak ...

can anyone explain me plz whats wrong with my distructor?
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
#include <iostream>
#include <string>
using namespace std;

class String {
public:
	int len;
	char* s;

public:
    String();
	void assign(char* mystr);
	inline int length ();
	void print ();
	~String();
};

    String::String(){
	s="No String Inserted";
	len=strlen(s);
	s=new char[255];
}

    String::~String(){
	delete s;
}

void String::assign(char* mystr){
	s=mystr;
	len=strlen(mystr);
}

inline int String::length(){
	int i =strlen(s);
	return i;
}
void String::print(){
	cout<<"the string: "<<s<<endl;
}

void printlength(String s){
	int i=s.len;
	cout<<i<<endl;
}


int main()
{
	
	String s1,s2;

	s1.assign("1234");
	s2.assign("123");
	if(s1.length()>s2.length())
		s1.print();
	else
	if (s1.length()==s2.length())
		cout<<"strings are equal "<<endl;
	else
		s2.print();

	return 0;
}
i also tried "delete [] s"...
Your constructor allocates memory and stores a pointer to it in s

Your 'assign()' member function replaces that pointer without deallocating the memory. This is where the memory leak takes place: the old value of the pointer is lost forever.

The destructor attempts to use delete on a pointer that was never allocated with new (this is where the behavior of the program becomes undefined)

Also, you're including <string> and never using it. Based on the functions you're calling, you meant to include <cstring>

Also, you're creating non-const pointers to string literals, which is an error in C++11
Last edited on
Topic archived. No new replies allowed.