添加printf语句

时间:2016-02-08 09:29:59

标签: c++ c

为什么在最后添加printf语句时会给出运行时错误?在删除printf语句之后,没有错误。

#include <stdio.h>

#define MOD 1000000007
#define MAX 44721

int main() {
    long long int test, i, j, store[1000009], n, m, x, a[1000006];
    scanf("%lld", &test);
    for (i = 0; i < 1000006; i++) {
        store[i] = 1LL;
    }
    a[0] = 1;

    for (j = 1; j < 1000006; j++) {
        for (i = 1; i < MAX; i++) {
            if (i % 2 == 0) {
                store[i] = (store[i - 1] + store[i]) % MOD;
            }
        }
        a[j] = store[MAX - 1];
    }
    printf("%lld", a[1]);
    return 0;
}

3 个答案:

答案 0 :(得分:1)

首先,你应该选择一种语言,因为C与C ++不同。 由于你的代码是C,我的解决方案也将在C语言中。

在Valgrind cleary下运行代码表明您遇到了堆栈溢出。堆栈上的数组大小太大。

Valgrind输出:

==14228== Invalid write of size 4
==14228==    at 0x100000DC7: main (prova.c:6)
==14228==  Address 0x1038c062c is on thread 1's stack
==14228==  in frame #0, created by main (prova.c:6)

堆栈的大小取决于系统,许多系统的默认值是8MB,在unix / linux上你可以看到它发出commnad ulimit -a。您可能需要查看此post以获取有关堆栈和堆如何工作的更多信息。

正确的解决方案是动态分配数组:

store = malloc(1000009 * sizeof(long long int));
if (store == NULL) {
  // The memory allocation failed, exit
  return(1);
}

a = malloc(1000006 * sizeof(long long int));
if (a == NULL) {
   return(1);
}

请务必检查malloc;)

的返回值

答案 1 :(得分:0)

这里有两个主要问题。

由于retrun 0,您的代码可能失败了; (修复:return 0;)

其次,你在堆栈中分配了2个非常大的数组,99%的时候,你最终会得到堆栈溢出;

注意:long long intlong long相同:

你应该考虑使用:

std::vector<long long> store(10000009);

std::unique_ptr<long long[]> store = std::make_unique<long long[]> (10000009);

   long long* store = new long long[10000009]

   auto* store = new long long[10000009]

或者如果你使用c ...因为你有两个标签

   long long* store = (long long *)malloc(sizeof(long long) * 10000009);

或者如果您使用的是MSVC,如果您想要的是64位[8字节]的int,则可以使用__int64关键字)

std::vector<__int64> store(1345134123);

我通常喜欢这么长时间

如果您最终使用其他编译器,则可以执行typedef long long __int64

答案 2 :(得分:0)

在自动存储中分配2个strand大型数组,超过8MB的堆栈空间。您可能会导致堆栈溢出。如果删除long long int,编译器可能会优化大部分代码,因为如果没有它,它们都没有任何可观察的行为。

在C中,使用printf分配数组:

malloc