I have some function like this:
void MClass::GetS(char* buf, int max) const {
char *temp = new char[max];
temp[max] = '\0';
for (int i = 0; i < max - 1; i++)
temp[i] = src[i]; // src is class member (char *)
buf = temp; // buf is null after this o.O
}
So, I can’t change buf value in this function. Why does it take place?
Problems:
You are writing off the end of your heap array with
temp[max] = '\0';– this places a 0 1 spot after your buffer.Who knows how big src is. You are passing in a “max” and reading against a src without check
size – very dangerous.
You are returning a pointer with a pointer. You need to pass in a double pointer and to get the actual pointer value returned correctly (or return the pointer in the return statement.)
When in doubt, trace your code in a debugger. My guess is that your compiler is helping you by opimizing the last assignment away and leaving it as NULL for you – then letting you merrily crash later on with your now corrupted heap and memory leak…