Here's a code i wrote, the sm_string(like std::string) class:
class sm_string
{
....
void _Add(sm_string a)
{// it adds the string to string(concatenates) and saves result in (*this)
printf("\n_Add %s %s\n",str,a());
str = (char*)ReallocSave(str,Len()+a.Len()+1,Len()+1);
memcpy(str+Len(),a(),a.Len()+1);
}
sm_string Add(sm_string a)
{// it concatenates too, return result,doesnt change (*this)
printf("\nAdd %s %s\n",str,a());
sm_string res(str);
res._Add(a);
return res;
}
sm_string(char* a)
{// creates string from char* string
str = (char*)malloc(strlen(a)+1);
memcpy(str,a,strlen(a)+1);
printf("Creating %s\n",str);
}
sm_string(int a)
{// creates string from int
char buf[100];
itoa(a,buf,10);
str = (char*)malloc(strlen(buf)+1);
memcpy(str,buf,strlen(buf)+1);
printf("Creating %s\n",str);
}
sm_string()
{//creates null string {'\0'}
str = (char*)malloc(1);
str[0] = '\0';
printf("Creating %s\n",str);
}
~sm_string()
{//frees the pointer
printf("\nFree of %s\n",str);
free(str);
}
.....
};
That's the my realloc function(cause normal realloc may lose the content while allocating more memory)
void* ReallocSave(void* pointer,int size,int oldsize)
{//realloc, which doesnt loose the memory
void* _instance = malloc(size);
memcpy(_instance,pointer,min(size,oldsize));
free(pointer);
return _instance;
}
It's the main function:
...
sm_string a("1");
a._Add(a.Add(3));
printf("%s",a());
...
And when i run this i receive an error
As you see the destructor of "113" - it's the string from main function - is called twice. At all there's 3 constructors calls and 4 destructors, how can i fix this?