Reputation:
My code gives me an error:
Debug assertion failed.
Expression: (L"String is not null terminated" && 0)
class Rectangle {
private:
char* objID;
}
Rectangle::Rectangle(const Rectangle& rect ) {
std::cout << "Copy constructor for: " << rect.objID << std::endl; // отладочный вывод
objID = new char[strlen(rect.objID) + strlen("(кoпия)") + 1];
strcpy_s(objID, strlen(objID), rect.objID);
strcat_s(objID, strlen(objID), "(копия)");
name = new char[strlen(rect.name) + 1];
strcpy_s(name,strlen(name), rect.name);
A=rect.A;
B=rect.B;
}
Upvotes: 0
Views: 472
Reputation:
objID = new char[strlen(rect.objID) + strlen("(кoпия)") + 1]; strcpy_s(objID, strlen(objID), rect.objID);
At the time of creation, objID
contains uninitialized memory. It is filled with random data. Therefore strlen(objID)
will not return the size allocated in the new
operation (strlen(rect.objID) + strlen("(copy)") + 1
), but will return the length of random data (terminated with \0
character).
int size=strlen(rect.objID) + strlen("(кoпия)") + 1;
objID = new char[size];
strcpy_s(objID, size, rect.objID);
Upvotes: 0
Reputation: 111860
It should be something like;
const char* psuffix = "(кoпия)";
size_t size = strlen(rect.objID) + strlen(psuffix) + 1;
objID = new char[size];
strcpy_s(objID, size, rect.objID);
strcat_s(objID, size, psuffix);
size_t size2 = strlen(rect.name) + 1;
name = new char[size2];
strcpy_s(name, size2, rect.name);
The second parameter of strcpy_s
/strcat_s
is the length of the buffer, including the space you reserved for the \0
.
Upvotes: 1