C 语言代码防止程序崩溃的最佳实践
以下是一些防止程序崩溃的 C 语言代码:
- 在循环中使用计数器,并确保计数器不会超出预期范围。
for(int i=0; i<10; i++){
// do something
}
- 在数组中使用数组长度,并确保不会超出数组范围。
int arr[5] = {1, 2, 3, 4, 5};
for(int i=0; i<5; i++){
// do something with arr[i]
}
- 检查输入的有效性,避免输入的数据超出程序可以处理的范围。
int num;
printf('Enter a number between 1 and 10: ');
scanf('%d', &num);
if(num < 1 || num > 10){
printf('Invalid input, please enter a number between 1 and 10.
');
}
- 使用条件语句来检查程序中可能出现的错误,并采取适当的措施。
int result = func();
if(result < 0){
printf('Error: func() returned a negative value.
');
exit(1);
}
- 使用断言来检查程序中的假设,并在假设不成立时终止程序。
#include <assert.h>
int func(int x){
assert(x > 0); // ensure that x is positive
// do something with x
}
int main(){
func(-1); // this will cause the program to terminate
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nNwb 著作权归作者所有。请勿转载和采集!