我们有 cpp dll,我可以在其中缩小到发生崩溃的行。该行与复制相关,即:
void GetCellText(HWND ssHwnd,char *& output){
CString sData;
....
....
strcpy (output, sData) //app crashes here
}
所以我像这样替换了 strcpy:
void copyToOutput(char *& output, CString sData) {
int strLen = sData.GetLength();
output = (char *) malloc(sizeof(char) * strLen + 1); // Allocate memory
LPTSTR p = sData.GetBuffer(strLen);
strcpy(output, p);
output[strLen] = '\0'; // Null terminate
sData.ReleaseBuffer();
}
但是我仍然看到崩溃故障。你能建议我的修复有什么不正确的地方吗?
最佳答案
该代码可能存在一些问题:
- 切勿使用
strcpy
因为它很容易导致目标缓冲区溢出。在您的情况下,您知道要复制的字符串的长度,没有理由不使用memcpy
,例如memcpy(output, p, strLen)
. - 这是 C++ 代码,但缓冲区是使用
malloc
分配的。此代码的调用者可能会意外使用free[]
解除分配它。您可能喜欢使用std::vector<char>
而不是原始指针。 - 您可以直接访问底层 C 字符串,而无需使用
CString::PCXSTR
进行复制.
关于c++ - 尝试使用 strcpy 时看到应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519574/