c++ - 尝试使用 strcpy 时看到应用程序崩溃

标签 c++ c dll

我们有 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();
}

但是我仍然看到崩溃故障。你能建议我的修复有什么不正确的地方吗?

最佳答案

该代码可能存在一些问题:

  1. 切勿使用strcpy因为它很容易导致目标缓冲区溢出。在您的情况下,您知道要复制的字符串的长度,没有理由不使用 memcpy ,例如memcpy(output, p, strLen) .
  2. 这是 C++ 代码,但缓冲区是使用 malloc 分配的。此代码的调用者可能会意外使用 free[]解除分配它。您可能喜欢使用std::vector<char>而不是原始指针。
  3. 您可以直接访问底层 C 字符串,而无需使用 CString::PCXSTR 进行复制.

关于c++ - 尝试使用 strcpy 时看到应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519574/

相关文章:

c++ - 如何执行与将 Windows 7 显示从横向更改为纵向相同的操作

c++ - Data.Aeson 在 ghc 中使用 ForeignFunctionInterface

c - 在函数调用中实例化一个结构体作为参数

C# NUnit 测试 : Mock a external DLL-Method who call a Socket connection to a extern Device

.net - 如何使自己的 .NET dll 全局化?

c# - 如何从 DLL 获取 MySqlConnection 对象

c++ - 不会命中 Visual Studio 2015 c++ 断点

c++ - 在 Windows 7 的 CodeBlocks 16.01 中构建 glfw3 程序失败

CGI 程序在curl_easy_init() 上崩溃

c - 在 GUROBI 的 C API 中添加约束需要太长时间