im trying to use the overloaded operator>>
to put the input stream into a char*
array.
Valgrind shows me that i get an Invalid write of size 1
at the line im assigning the input stream to my char* array
.
My Code for this looks like the following. (Shorted)
In my string.h im defining the functions.
#ifndef STRING_H_INCLUDED
#define STRING_H_INCLUDED
#include<iostream>
#include<istream>
#include<ostream>
class string{
public:
string(char* = nullptr);
~string();
string(const string&);
friend std::istream& operator>>(std::istream&,string&);
void copyStr(char*);
char* getContent() const;
...
private:
string& operator=(const string&);
char* s = nullptr;
};
#endif // STRING_H_INCLUDED
The actual c++ file looks like this.
#include<iostream>
#include<ostream>
#include "string.h"
string::string(char* i){
if(i == nullptr){
s = new char[1];
s[0] = '\0';
}else{
s = new char[getCharl(i)+1];
copyStr(i);
}
}
string::~string(){
if(s != nullptr){
delete[] s;
}
}
string::string(const string& x){
copyStr(x.getContent());
}
std::istream& operator>>(std::istream& is, string& arg){
is >> arg.getContent();
return is;
}
void string::copyStr(char* i){
unsigned index = 0;
delete[] s;
char* tmp = new char[getCharl(i)+1];
while (i[index] != '\0'){
tmp[index] = i[index];
index++;
}
tmp[index] = '\0';
s = tmp;
}
char* string::getContent() const{
return s;
}
...
Maybe someone would be so kind to create a small example to show me how it works with a little explanation.
Cheers!
Edit:
Added the getContent()
function.