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

Catch c++ exception by allocating c memory error

本文关键字:c++ 异常 错误 内存 分配      更新时间:2023-10-16

我为接收数据分配了一个char指针。当数据太大时,我会收到Segmentation错误(核心转储)。我尝试使用try-catch块来捕获异常以避免这种错误,但仍然显示相同的错误。如何捕捉这种异常?

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

通常捕获分段错误是个坏主意,因为您无法保证程序中的任何数据仍然有效。所以你们不能仅仅截取SIGSEGV信号,然后像往常一样工作。

点击此处查看更多详细信息:如何在Linux中发现分段错误?

您无法通过异常捕获分段错误。。。异常并不是为了捕捉信号而设计的。对于这些情况,您需要特殊处理,如呼叫信号处理程序等…

尽管在C++中有一种方法可以将这些信号转换为异常。以下链接将对此主题进行说明:-

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

示例如下:-

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

无论如何,在出现分段错误后,最好进行调试,而不是继续当前执行,然后成为transported to realm of undefined behavior.

您无法在C++中捕获Segmentation错误。seg错误是由于程序运行的错误操作导致内存损坏的结果。此时,操作系统已经控制了您的程序。您不希望在seg故障后继续运行程序,因为状态不稳定。作为程序员,您需要避免seg错误。

如果您发布的代码是您的实际代码,即使您分配了足够的空间,您的代码也不会正常工作。

 void setmemory(char *p, int num)
 {
     p=(char*)malloc(num);
 }
  int main()
  {
    char* str = NULL;
    setmemory(str,1);
    //...
    strcpy(str,"hello");

我们可以在那里停下来。您正试图将"hello"复制到一个NULL指针。即使调用了setmemory函数,也不会将str设置为已分配的空间。

正确的方法(我会使用malloc,尽管我不推荐它)是:

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

您需要通过引用传递指针,否则p将充当临时变量,因此在函数中设置p将不会传播回调用方。