开发者

Throw in C++ triggers program message then crash

I debugged my application and the code crashes instantly upon the throw statement inside of this code:

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;
     }
}

So, upon debugging it crashes right on the throw statement. Interestingly enough, the CLI (in this case, 'cmd.exe') shows this message (which was not put in there by me, and is either from the compiler开发者_C百科 or the OS):

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

I'm leaning more towards C++ now, as I used to just program in C. As you can tell, right now I am trying to manage the try-catch exception handling system that C++ uses.


Your if statement looks incorrect: the name newbuff indicates a pointer, and the size of that will be 4 on a 32-bit system or 8 on a 64-bit system. Oh, right, after I posted that you've edited you code to show the definition of newbuff as an array. But anyway.

The throw can crash if there is no handler. In this case the standard does not require that the stack is rewound (local objects destroyed).

It seems that BUFFER_TOO_SMALL is a constant, probably an integer. You should not throw integers (unless you really know what you're doing). Throw std::exception objects, e.g. std::runtime_error.

Edit: Your updated code shows that you're catching int. That means your uppercase constants are not int. But the advice stands anyway.

There is also a style issue, the use of ALL UPPERCASE for a constant. Don't. That's a Java-ism: in C and C++ by convention all uppercase is for macros and macros only.

Cheers & hth.,


It seems that newbuff don't have space for NULL terminator. you should resize newbuff[8] to newbuff[9].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜