当cout语句被注释掉时,c++程序与malloc一起崩溃



我有一个运行良好的程序。但是,如果我注释掉一个cout语句(请参阅下面的代码(,它就会抛出错误。它也在ideone上尝试过,结果也是一样。

代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> ugly_numbers = vector<int>(n, 0);
ugly_numbers[0] = 1;
int ugly2 = 0, ugly3 = 0, ugly5 = 0, ugly_count = 1;
while (ugly_count <= n) {
int next_ugly_num_2 = ugly_numbers[ugly2] * 2;
int next_ugly_num_3 = ugly_numbers[ugly3] * 3; 
int next_ugly_num_5 = ugly_numbers[ugly5] * 5; 
int next_ugly_num = min(min(next_ugly_num_2, next_ugly_num_3), next_ugly_num_5);

if (next_ugly_num == next_ugly_num_2) ugly2++;
if (next_ugly_num == next_ugly_num_3) ugly3++;
if (next_ugly_num == next_ugly_num_5) ugly5++;
//cout << ugly_count << " - ";             //*********THIS COUT IS WIERD**********
ugly_numbers[ugly_count] = next_ugly_num;
ugly_count++;
}
cout << ugly_numbers[n - 1] << endl;
return 0;
}

错误:

a.out: malloc.c:2401: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
The terminal process "/bin/bash '-c', ' g++ -g Cpp/a.cpp -o a.out && clear && timeout 10 /usr/bin/time -v --output sys.txt ./a.out < input.txt > output.txt && rm *out'" terminated with exit code: 134.

为什么会发生这种情况?为什么cout语句会影响程序的行为?我该如何纠正?

ugly_count等于n时修改ugly_numbers[ugly_count]时,在上一次循环迭代中会出现未定义的行为。这种未定义的行为可能是可见的,也可能是不可见的:它取决于n的值、vector的实现方式以及许多其他不可能的因素。这可以解释为什么只得到一个没有输出语句的错误。

您应该运行从0n的循环(排除(,或者使向量大一个元素:

#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> ugly_numbers = vector<int>(n + 1, 0);
ugly_numbers[0] = 1;
int ugly2 = 0, ugly3 = 0, ugly5 = 0;
for (int ugly_count = 1; ugly_count <= n; ugly_count++) {
int next_ugly_num_2 = ugly_numbers[ugly2] * 2;
int next_ugly_num_3 = ugly_numbers[ugly3] * 3; 
int next_ugly_num_5 = ugly_numbers[ugly5] * 5; 
int next_ugly_num = min(min(next_ugly_num_2, next_ugly_num_3), next_ugly_num_5);

if (next_ugly_num == next_ugly_num_2) ugly2++;
if (next_ugly_num == next_ugly_num_3) ugly3++;
if (next_ugly_num == next_ugly_num_5) ugly5++;
//cout << ugly_count << " - ";
ugly_numbers[ugly_count] = next_ugly_num;
}
cout << ugly_numbers[n - 1] << endl;
return 0;
}

相关内容

  • 没有找到相关文章

最新更新