I have wrote class myString which override some operators. The result is wrong if it run in vs2013(Microsoft Virtual Studio 2013). But the result is right if it run in devcpp. why?
By the way, I have debug, and find the problem is realloc. The data which was existed in memory become invalid After realloc in vs2013.
all my code:
#include <iostream>
#include<string>
#include <stdlib.h>
#include <string.h>
using namespace std;
class myString{
public:
myString() :_str(NULL), length(0){};
myString(char* str);
friend myString& operator+(myString& str,char* s);
friend myString& operator+(myString& str, myString& s);
friend myString& operator+(myString& str, int num);
friend ostream& operator<<(ostream& out,myString& str);
void operator=(char* s);
void operator=(myString& s);
private:
char* _str;
int length;
};
myString::myString(char* str){
if (str == NULL){
_str = NULL;
length = 0;
return;
}
length = strlen(str);
_str = (char*)malloc(sizeof(char)*length);
strcpy(_str, str);
}
myString& operator+(myString& str, char* s){
if (s == NULL)
return str;
char* temp = (char*)realloc((void*)str._str, sizeof(char)*strlen(s));
if (temp == NULL){
cout << "error" << endl;
return str;
}
str.length += strlen(s);
strcat(temp, s);
str._str = temp;
return str;
}
myString& operator+(myString& str, myString& s){
if (s.length == 0 || s._str == NULL)
return str;
char* temp = (char*)realloc((void*)str._str, sizeof(char)*strlen(s._str));
if (temp == NULL){
cout << "error" << endl;
return str;
}
str.length += strlen(s._str);
strcat(temp, s._str);
str._str = temp;
return str;
}
myString& operator+(myString& str, int num){
char* s = (char*)malloc(sizeof(char) * 100);
itoa(num, s, 10);
/******problem! in vs2013, after realloc str._str become invalid.
But in devcpp everything is right. Why???******/
char* temp = (char*)realloc((void*)str._str, sizeof(char)*strlen(s));
if (temp == NULL){
cout << "error" << endl;
return str;
}
str.length += strlen(s);
strcat(temp, s);
str._str = temp;
return str;
}
void myString::operator=(char* s){
if (s == NULL)
return;
this->length += strlen(s);
this->_str = (char*)malloc(sizeof(char)*strlen(s));
strcpy(this->_str, s);
}
void myString::operator=(myString& s){
this->length = s.length;
this->_str = s._str;
}
ostream& operator<<(ostream& out, myString& str){
out << "string is:" <<str._str<<", length is:"<<str.length;
return out;
}
int main(){
myString str;
str = "hello world";
cout << str << endl;
str = str+ 123;
cout << str << endl;
system("pause");
return 0;
}