i am facing problems of destructor in the following code.destructor is not working.can any one help plz????

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;

class strtype
{
private:
	char *p;
	int len;
public:
	strtype()
	{
		p=(char *)malloc(sizeof(char));
		*p='\0';
		len=0;
	}
	void getString(char *str)
	{
		len=strlen(str);
	
		p=(char *)realloc(p,sizeof(char)*len);
	
		strcpy(p,str);
	}
	void showString()
	{
		cout<<p<<endl;
		cout<<strlen(p)<<endl;
	}
	~strtype()
	{
		cout<<"freeing p";
		free(p);
	}

};

int main()
{
	strtype s1,s2;

	s1.getString("my name is arafat");
	s2.getString("jawad votka");


	s1.showString();
	s2.showString();


	return 0;
}

Recommended Answers

All 3 Replies

i am facing problems of destructor in the following code.destructor is not working

The memory allocation is one byte off, you need to allocate an additional byte for the null terminator placed there by strcpy() , so

len = strlen(str) + 1;

FYI, sizeof(char) is always one (1), so you can drop sizeof(char) altogether.

In the constructor, len is rather 1 than 0, though this does not affect the program as of now.

Then last but not least, it's a good practice to check whether the memory re/allocation succeeds. If they don't, the program crashes.

[EDIT]
Since this is C++, maybe rewrite the program using new/delete or std::string .

My toe hurts, can you tell me why?

That question is admittedly a little worse than yours, but not by much. Tell us what sort of a problem are you having---Program crashing? Not compiling? Runs okay but gives wrong output? Error/warning messages?

Some ideas, that may or may not have anything to do with your problem.

First, since this is C++ using new and delete or new[] and delete[] would be recommended instead of malloc, realloc, free.

suggest change line 13 and 14 to just: p = NULL; or p = 0;

In getString() check to see if p == NULL and delete memory already assigned to p if not before reallocating memory to it to prevent memory leak.

In the destructor use delete[] p;

commented: Metatarsalgia? Oh it was rhetorical. I get it :) +2

thanks for helping gyes...its working....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.