【发布时间】:2015-01-09 12:28:08
【问题描述】:
我分配一个字符指针来接收数据。当数据太大时,我会收到分段错误(核心转储)。我尝试使用 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;
}
【问题讨论】:
-
如果您确实在使用
C++而不是C,请停止使用malloc和char*并开始使用string。 -
您设置的内存函数不会更新您在 main 中传递给它的指针。你需要通过
char*& p -
使用
char *strncpy( char *dest, const char *src, std::size_t count );定义要复制的字符数(根据您制作的malloc) -
如果你需要在函数中改变指针指向的东西,你需要一个指向指针的指针或者一个指针的引用。否则,您在
setmemory中对p的分配不会影响调用者。 -
你不能真的希望从中恢复过来。此时放弃并终止进程。