【发布时间】:2021-11-06 00:00:27
【问题描述】:
在源代码下面(我已经在代码上注释了错误),我明白了
第 27 行:字符 33:运行时错误:有符号整数溢出:-1094795586+ -1094795586 无法以“int”类型表示
我查阅了不同的文章,例如 How to detected signed integer overflow,但我没有得到要检查的整数。working_array[] 的元素如果其值小于 target 整数,则从 nums[] 中过滤。
由于nums[] 的元素类似于[ 3, 6, 11, 19, 2, ...],我不担心在最后一个if 语句的SUM 期间检查溢出。我错了吗?
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int count_elem = 0;
int *working_array = (int*)malloc(numsSize * sizeof(int));
// Going through original array
for(int i=0;i<numsSize;i++){
// If elem nums[i] is less than target, is accepted on a new working array
if(nums[i] < target){
count_elem += 1;
working_array[count_elem] = nums[i];
}
}
working_array = realloc(working_array, count_elem*sizeof(int));
// Creating result array
returnSize = sizeof(int)*2;
int *result_array = (int*)malloc(returnSize);
// Going through working array
for(int i=0;i<count_elem;++i)
for(int j=0;j<count_elem;++j)
// SIGNED INTEGER OVERFLOW IN LINE BELOW
if( (working_array[i]+working_array[j]) == target){
result_array[0] = working_array[i];
result_array[1] = working_array[j];
free(working_array);
return result_array;
}
free(working_array);
return;
}
P.S:我知道cast malloc results 没用,但这可能是个小问题。
【问题讨论】:
-
returnSize = sizeof(int)*2;:但returnSize是指针?你应该得到一个大的红色警告。 -
是的,我错过了。通过使用
sizeof(int)*2代替returnSize指针,问题仍然存在...... -
很多人不相信有符号整数溢出是可能的,或者问如何检测。然而,您的平台似乎已被检测到并很好地诊断出来,甚至无需您询问!这是什么平台?
-
@SteveSummit 这个帖子的错误,与 LeetCode 网站的调试器有关。我正在解决一个练习。 (请注意,我的问题是关于编译错误,而不是关于如何解决练习本身)
标签: c integer-overflow