【问题标题】:Windows has triggered a breakpoint due to corruption in heap or dlls loaded由于堆损坏或加载的 dll,Windows 已触发断点
【发布时间】:2012-05-03 12:59:19
【问题描述】:

我有一个 C++ 文件,其中包含一些我在 C# 中调用的导出函数。其中一个功能是:

char segexpc[MAX_SEG_LEN];

extern "C" QUERYSEGMENTATION_API char* fnsegc2Exported()
{
    return segexpc2;
}

在程序的某个地方,我也在做这个事情:

if(cr1==1)
{
strcpy(segexpc, seg);
}

在我的 C# 程序中,我通过以下方式调用上述内容:

[DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern StringBuilder fnsegcExported();

this.stringbuildervar = fnsegcExported();

以前,我没有收到任何错误,但现在我在 Visual Studio 中调试时突然开始收到此错误。

Windows has triggered a breakpoint in SampleAppGUI.exe.
This may be due to a corruption of the heap, which indicates a bug in SampleAppGUI.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while SampleAppGUI.exe has focus.

此错误仅在必须显示窗口之前的末尾出现。我没有按任何 F12 键,也没有在此处设置任何断点,但我不确定为什么此时会发生错误并中断。 this.stringbuildervar = fnsegcExported();
当我按下继续时,会出现带有正确输出的窗口。

【问题讨论】:

    标签: c# c++


    【解决方案1】:

    如果你改变了你的外部声明会发生什么

    [DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern StringBuilder fnsegcExported();
    

    [DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern string fnsegcExported();
    

    然后按如下方式调用:

    this.stringbuildervar = new StringBuilder(fnsegcExported());
    

    string 似乎是更合适的类型。或者更好的是使用 Marshal 类将您的非托管 char* 返回编组为托管字符串。

    [DllImport("QuerySegmentation.dll", EntryPoint = "fnsegcExported", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern IntPtr fnsegcExported();
    
    string managedStr = Marshal.PtrToStringAnsi(fnsegcExported);
    this.stringbuildervar = new StringBuilder(managedStr);
    

    【讨论】:

      【解决方案2】:

      您在此行看到错误的原因是它是您拥有调试信息的最后一个堆栈帧。

      幸运的是,就您而言,C++ 端的代码很少。确保segexpc 包含一个以零结尾的字符串。

      我怀疑因为字符串生成器的默认容量是 16,您可能无法以这种方式返回更长的字符串。也许您只想返回字符串。

      我还想知道您的 C++ 字符串是否必须是非 Unicode。这会损害每次转化时的性能。

      【讨论】:

      • @jarika:我并不完全熟悉 C++,但我想知道 strcpy 是否会复制到\0。如果没有,C++ 中是否有任何函数可以自动复制目标字符串并将其设为空终止字符串?
      • strcpy 将为您添加空终止符 (\0) Copies the C string pointed by source into the array pointed by destination, including the terminating null character
      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多