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

using namespace std;

class strtype
	char *p;
	int len;
		p=(char *)malloc(sizeof(char));
	void getString(char *str)
		p=(char *)realloc(p,sizeof(char)*len);
	void showString()
		cout<<"freeing p";


int main()
	strtype s1,s2;

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


	return 0;

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.

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....