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

标签 c++ c

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

#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 信号就照常工作。

在此处查看更多详细信息: How to catch segmentation fault in Linux?

关于c++ - 通过分配c内存错误捕获c++异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890604/

相关文章:

c# - 在C#中通过继承向类添加私有(private)方法

c++ - 如何根据用户请求安全地停止正在运行的线程?

c++ - 在 C++ 中抛出异常时释放本地缓冲区

c# - 在 C#(WPF) 中使用 C++ dll

c - 如何在网络上对 float 进行序列化?

.net - 从 Windows C 函数返回字符串

c++ - C++ 的 Activator.CreateInstance?

c - 在C中,读取字符和整数时变量值会发生变化

克隆系统调用和互斥

c - 为什么我的 rgb 到 uint32 预处理器宏给我错误的颜色代码?