C:在处理大数字时避免溢出 [英] C: avoiding overflows when working with big numbers

查看:30
本文介绍了C:在处理大数字时避免溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 C 中实现了一些排序算法(对整数进行排序),小心地使用 uint64_t 来存储与数据大小有关的任何东西(因此也包括计数器和东西),因为还应使用几千兆整数的数据集测试算法.

I've implemented some sorting algorithms (to sort integers) in C, carefully using uint64_t to store anything which has got to do with the data size (thus also counters and stuff), since the algorithms should be tested also with data sets of several giga of integers.

算法应该没问题,分配的数据量应该没有问题:数据存储在文件中,我们每次只加载小块,即使我们阻塞内存缓冲区,一切正常任何尺寸.

The algorithms should be fine, and there should be no problems about the amount of data allocated: data is stored on files, and we only load little chunks per time, everything works fine even when we choke the in-memory buffers to any size.

使用高达 4 giga ints(因此 16GB 的数据)的数据集进行测试工作正常(对 4Gint 进行排序需要 2228 秒,约 37 分钟),但是当我们超过该值(即:8 Gint)时,算法似乎没有停止(现在已经运行了大约 16 个小时).

Tests with datasets up to 4 giga ints (thus 16GB of data) work fine (sorting 4Gint took 2228 seconds, ~37 minutes), but when we go above that (ie: 8 Gints) the algorithm doesn't seem to halt (it's been running for about 16 hours now).

恐怕问题可能是由于整数溢出,也许循环中的计数器存储在 32 位变量中,或者我们正在调用一些处理 32 位整数的函数.
还能是什么?

I'm afraid the problem could be due to integer overflow, maybe a counter in a loop is stored on a 32 bits variable, or maybe we're calling some functions that works with 32 bits integers.
What else could it be?

有没有什么简单的方法可以检查运行时是否发生整数溢出?

Is there any easy way to check whether an integer overflow occurs at runtime?

推荐答案

这是特定于编译器的,但是如果您使用的是 gcc,那么您可以使用 -ftrapv 进行编译以发出 SIGABRT 当有符号整数溢出发生时.

This is compiler-specific, but if you're using gcc then you can compile with -ftrapv to issue SIGABRT when signed integral overflow occurs.

例如:

/* compile with gcc -ftrapv <filename> */
#include <signal.h>
#include <stdio.h>
#include <limits.h>

void signalHandler(int sig) {
  printf("Overflow detected
");
}

int main() {
  signal(SIGABRT, &signalHandler);

  int largeInt = INT_MAX;
  int normalInt = 42;
  int overflowInt = largeInt + normalInt;  /* should cause overflow */

  /* if compiling with -ftrapv, we shouldn't get here */
  return 0;
}

当我在本地运行这段代码时,输​​出是

When I run this code locally, the output is

Overflow detected
Aborted

这篇关于C:在处理大数字时避免溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆