0

我调试了我的应用程序,代码在这段代码中的 throw 语句立即崩溃:

try
{
    char newbuff[8];
    if(strlen(cstr) > sizeof(newbuff))
    {
         throw BUFFER_TOO_SMALL;
    }
    if(strlen(cstr) == 0)
    {
         throw NO_CONTENT;
    }
    strcpy(newbuff, cstr); //Yeah yeah yeah, I know, I'm just learning
    ptr = newbuff;
}
catch(int errn)
{
     cout << "error: ";
     if(errn == BUFFER_TOO_SMALL)
     {
          cout << "storage buffer too small.\n";
          return 0;
     }
     if(errn == NO_CONTENT)
     {
          cout << "no content inside of buffer.\n";
          return 0;
     }
}

因此,在调试时,它会throw 语句上崩溃。有趣的是,CLI(在本例中为“cmd.exe”)显示了这条消息(不是我放在那里的,它来自编译器或操作系统):

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

我现在更倾向于 C++,因为我以前只是用 C 编程。如您所知,现在我正在尝试管理 C++ 使用的 try-catch 异常处理系统。

4

2 回答 2

0

您的if陈述看起来不正确:名称newbuff表示一个指针,它的大小在 32 位系统上为 4,在 64 位系统上为 8。哦,对了,在我发布您编辑代码以将定义显示newbuff为数组之后。但不管怎么说。

throw如果没有处理程序,可能会崩溃。在这种情况下,标准不要求堆栈被倒回(本地对象被破坏)。

这似乎BUFFER_TOO_SMALL是一个常数,可能是一个整数。你不应该抛出整数(除非你真的知道你在做什么)。扔std::exception物体,例如std::runtime_error.

编辑:您更新的代码显示您正在捕获int. 这意味着您的大写常量不是int. 但建议仍然有效。

还有一个样式问题,使用 ALL UPPERCASE 作为常量。不。那是一种 Java 主义:在 C 和 C++ 中,按照惯例,所有大写字母都仅用于宏和宏。

干杯&hth.,

于 2011-06-21T01:21:16.763 回答
0

似乎 newbuff 没有空终止符的空间。您应该将 newbuff[8] 的大小调整为 newbuff[9]。

于 2011-06-21T01:38:33.967 回答