C:有大的数字工作时避免溢出 [英] C: avoiding overflows when working with big numbers

查看:238
本文介绍了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个千兆整型(这样的数据16GB)正常工作(整理4Gint了2228秒,〜37分钟),但是当我们去上面(即:8 Gints)算法好像没有不暂停(它已经运行了大约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\n");
}

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;
}

当我在本地运行此code,输出的是

When I run this code locally, the output is

Overflow detected
Aborted

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

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