I have to write a function that fills a char* buffer for an assigned length with the content of a string. If the string is too long, I just have to cut it. The buffer is not allocated by me but by the user of my function. I tried something like this:
int writebuff(char* buffer, int length){
string text="123456789012345";
memcpy(buffer, text.c_str(),length);
//buffer[length]='\0';
return 1;
}
int main(){
char* buffer = new char[10];
writebuff(buffer,10);
cout << "After: "<<buffer<<endl;
}
my question is about the terminator: should it be there or not? This function is used in a much wider code and sometimes it seems I get problems with strange characters when the string needs to be cut.
Any hints on the correct procedure to follow?
std::
, nonew
, no<<
(except maybe if you mean bitwise shift), ... – Fivefoldwritebuff
should do whatever it is advertised to do. If the caller expects a terminator, thenwritebuff
must supply it. If the caller expects no terminator thenwritebuff
must not supply it. In this specific case, the caller clearly expects a terminator (operator<<(ostream, char*)
expects a terminator). – Cardiology