void inf_int:: Sub(const char num, const unsigned int index)
{
if (this->length < index) {
this->digits = (char*)realloc(this->digits, index + 1);
if (this->digits == NULL) {
cout << "Memory reallocation failed, the program will terminate." << endl;
exit(0);
}
this->length = index;
this->digits[this->length] = '\0';
}
if (this->digits[index - 1] < '0') {
this->digits[index - 1] = '0';
}
this->digits[index - 1] -= num - '0';
if (this->digits[index - 1] < '0') {
this->digits[index - 1] += 10;
Sub('1', index + 1);
}
}
在第四行中,编译器返回错误,realloc 可以返回 null。我添加了第五行 if 为了处理这种情况,并在这种情况下退出程序,但它似乎不起作用。有人可以给我任何关于如何解决这个问题的指示吗?谢谢。
功能realloc
在这种情况下可以返回空指针,如果将函数调用的返回值分配给初始指针,则先前分配的内存的地址将丢失。您需要使用中间指针,例如
char *tmp = (char*)realloc(this->digits, index + 1);
if (tmp == NULL) {
cout << "Memory reallocation failed, the program will terminate." << endl;
// free( this->digits ); provided that the destructor does not call free itself
exit(0);
}
this->digits = tmp;
//...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)