简体   繁体   English

通过分配C内存错误来捕获C ++异常

[英]Catch c++ exception by allocating c memory error

I allocate a char pointer for receiving data. 我分配了一个char指针来接收数据。 When the data is too large, I'll receive the Segmentation fault (core dumped). 当数据太大时,我将收到分段错误(核心已转储)。 I try to use a try catch block to catch the exception to avoid this kind of error, but the same error still shows. 我尝试使用try catch块来捕获异常,以避免此类错误,但是仍然显示相同的错误。 How do I catch this kind of exception? 如何捕获这种异常?

#include<iostream>
using namespace std;

void setmemory(char* p, int num)
{
    p=(char*)malloc(num);
}

void test(void)
{
    char* str = NULL;
    setmemory(str,1);
    try{
        strcpy(str,"hello");
        cout << "str:" << str << endl;
    } catch (...) {
        str = NULL;
        cout << "Exception occured!" << endl;
    }
 }

 int main()
 {
    test();
    return 0;
 }

You cannot catch segmentation fault through exception... Exceptions are not designed to catch signals. 您无法通过异常捕获分段错误...异常并非旨在捕获信号。 For these cases you need special handling like calling signal handler etc... 对于这些情况,您需要特殊处理,例如调用信号处理程序等。

Although there is a way to convert these signals into exceptions in C++. 尽管有一种方法可以将这些信号转换为C ++中的异常。 Following link would illustrate on this topic:- 以下链接将说明该主题:-

https://code.google.com/p/segvcatch/

Example given in this:- 在此示例:

try
{
    *(int*) 0 = 0;
}
catch (std::exception& e)
{
    std::cerr << "Exception catched : " << e.what() << std::endl;
}

Anyway after getting segmentation fault it's better to go for debugging rather than continue with current execution and later be transported to realm of undefined behavior. 无论如何,在遇到分段错误之后,最好进行调试,而不是继续当前的执行,然后再transported to realm of undefined behavior.

Generally catching of Segmentation Fault is bad idea because you have no guaranty that any data in your program still valid. 通常,捕获Segmentation Fault是一个坏主意,因为您无法保证程序中的任何数据仍然有效。 So you cannot just intercept SIGSEGV signal and do you work as usual. 因此,您不能仅截获SIGSEGV信号,就可以照常工作。

See more details here: How to catch segmentation fault in Linux? 在此处查看更多详细信息: 如何在Linux中捕获分段错误?

You cannot catch a Segmentation fault in C++. 您不能在C ++中遇到分段错误。 A seg fault is a result of memory corruption due to a bad operation run by your program. 段错误是由于程序运行错误而导致的内存损坏。 At that point, the operating system has taken control of your program. 此时,操作系统已控制了您的程序。 You don't want to keep a program running after a seg fault because the state is unstable. 您不希望在段错误后使程序保持运行,因为状态不稳定。 You as the programmer need to avoid seg faults. 您作为程序员需要避免seg错误。

If the code you posted is your actual code, even if you allocated enough space, your code will not work correctly. 如果您发布的代码是您的实际代码,即使您分配了足够的空间,您的代码也将无法正常工作。

 void setmemory(char *p, int num)
 {
     p=(char*)malloc(num);
 }

  int main()
  {
    char* str = NULL;
    setmemory(str,1);
    //...
    strcpy(str,"hello");

We can stop right there. 我们可以就此停下来。 You are attempting to copy "hello" to a NULL pointer. 您正在尝试将“ hello”复制到NULL指针。 You are not setting str to the allocated space, even though the setmemory function was called. 即使调用了setmemory函数,也不setmemory str设置为分配的空间。

The proper way to do this (I will use the malloc , even though I don't recommend it) would be: 做到这一点的正确方法(即使我不推荐,我也会使用malloc ):

 void setmemory(char *&p, int num)
 {
     p=(char*)malloc(num);
 }

You need to pass the pointer by reference, otherwise p acts as a temporary variable, so setting p within the function will not propagate back to the caller. 您需要按引用传递指针,否则p充当临时变量,因此在函数内设置p不会传播回调用方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM