通过分配c内存错误捕获c++异常
Catch c++ exception by allocating c memory error
我为接收数据分配了一个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
将不会传播回调用方。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常