【发布时间】:2014-11-30 15:12:31
【问题描述】:
这个小项目基于this discussion,关于在执行操作之前检测整数溢出的最佳方法。我想要做的是有一个程序演示使用整数检查的有效性。它应该对某些数字产生未经检查的整数溢出,而如果使用检查(-c)标志,它应该在执行操作之前退出。 -m 用于乘法。
程序在没有布尔部分的情况下运行良好,但我需要一些关于执行最高OneBitPosition 检查的布尔部分的帮助。添加真/假逻辑后出现编译错误。我不确定我是否正确调用和使用了highestOneBitPosition 函数。谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*boolean */
#define true 1
#define false 0
typedef int bool;
void ShowUsage ()
{
printf (
"Integer Overflow Check before performing an arithmetic.\n"
"=======================================================\n"
"Usage:\n"
"Integer Operant (-a, -s, -m, -d) Checked/Unchecked (-u, -c)\n"
"Example: ./overflowcheck 2 -a 2 -u\n"
"\n"
);
}
size_t highestOneBitPosition(uint32_t a) {
size_t bits=0;
while (a!=0) {
++bits;
a>>=1;
};
return bits;
}
int main(int argc, char *argv[]) {
if (argc != 5) {ShowUsage (); return (0);}
else if (strcmp(argv[2],"-m") == 0 && strcmp(argv[4],"-u") == 0)
{printf("%s * %s = %d -- Not checked for integer overflow.\n",argv[1],argv[3], atoi(argv[1])*atoi(argv[3]));return 0;}
/*Works fine so far */
else if (strcmp(argv[2],"-m") == 0 && strcmp(argv[4],"-c") == 0)
{
bool multiplication_is_safe(uint32_t a, uint32_t b) {
a = atoi( argv[1] );
b = atoi( argv[3] );
size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
return (a_bits+b_bits<=32);}
if (multiplication_is_safe==true)
{printf("%s * %s = %d -- Checked for integer overflow.\n",argv[1],argv[3], atoi(argv[1])*atoi(argv[3]));return 0;}
if (multiplication_is_safe==false)
{printf("Operation not safe, integer overflow likely.\n");}
}
ShowUsage ();
return (0);}
编译:
gcc integer_overflow2.c -o integer_overflow
integer_overflow2.c:40:61: error: function definition is not allowed here
bool multiplication_is_safe(uint32_t a, uint32_t b) {
^
integer_overflow2.c:45:17: error: use of undeclared identifier
'multiplication_is_safe'
if (multiplication_is_safe==true)
^
integer_overflow2.c:47:17: error: use of undeclared identifier
'multiplication_is_safe'
if (multiplication_is_safe==false)
^
【问题讨论】:
-
您是否尝试定义嵌套函数? C 不支持。
-
main里面的这个函数声明是什么??? -
if (multiplication_is_safe==true)-->if (multiplication_is_safe(0,0)==true),if (multiplication_is_safe==false)-->else, and#include <stdint.h>还有#include <stdbool.h>
标签: c integer-overflow