gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:25:35 26 4
gpt4 key购买 nike

我分配了一个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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com