[英]Why does my c code crash when run from VSCode terminal, but runs fine when run from gnome terminal?
Memory seems to run out when I run the executable from within the Visual Studio Code terminal, and then my computer freezes.当我从 Visual Studio Code 终端运行可执行文件时,Memory 似乎用完了,然后我的电脑死机了。
But all is fine when I run it from gnome terminal, and I get the desired outputs.但是当我从 gnome 终端运行它时一切都很好,我得到了所需的输出。
I'm not yet knowledgeable about c or the gmp.h library.我还不了解 c 或 gmp.h 库。 I wouldn't be surprised if there is a bug somewhere, or something I am missing, even if the code I've posted does give me correct results when not run from VSCode.
如果某处存在错误或我遗漏了什么,我不会感到惊讶,即使我发布的代码在不从 VSCode 运行时确实给了我正确的结果。
Btw it does take about 1m43s to run, with N 666666, on my pc.顺便说一句,在我的电脑上运行 N 666666 确实需要大约 1 分 43 秒。
// problem from: https://www.reddit.com/r/dailyprogrammer/comments/jfcuz5/20201021_challenge_386_intermediate_partition/
#include "gmp.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define N 666666
mpz_t results[N + 1];
void segment(int n)
{
if (n <= 1)
return;
if (mpz_cmp_ui(results[n - 1], 0) > 0)
return;
mpz_t result;
mpz_t diff;
mpz_init(result);
mpz_init(diff);
int i = 0;
int seq = 1;
int is_positive;
while (n - seq >= 0)
{
segment(n - seq);
is_positive = 1 - 2 * (i / 2 % 2);
mpz_mul_si(diff, results[n - seq - 1], is_positive);
mpz_add(result, result, diff);
seq += (i % 2 > 0) ? i + 2 : (i + 2) / 2;
i += 1;
mpz_set_ui(diff, 0);
}
mpz_add_ui(results[n - 1], result, 0);
mpz_clear(result);
mpz_clear(diff);
return;
}
int main(void)
{
for (int i; i < N; i++)
{
mpz_init(results[i]);
}
mpz_set_ui(results[0], 1);
mpz_set_ui(results[1], 1);
for (int i; i <= N + 1; i++)
{
segment(i);
}
gmp_printf("Result: %Zd\n", results[N]);
for (int i; i < N; i++)
{
mpz_clear(results[i]);
}
}
The code has undefined behavior because the for
loops do not initialize the i
loop index: for (int i; i < N; i++)
Furthemore, the array has N + 1
elements, so the initialization loop should run one step farther and the segment loop one less.代码具有未定义的行为,因为
for
循环不会初始化i
循环索引: for (int i; i < N; i++)
此外,数组有N + 1
元素,因此初始化循环应该再运行一步,并且段少循环一圈。
Modify the main()
function to:将
main()
function修改为:
int main() {
for (int i = 0; i < N + 1; i++) {
mpz_init(results[i]);
}
mpz_set_ui(results[0], 1);
mpz_set_ui(results[1], 1);
for (int i = 0; i < N + 1; i++) {
segment(i);
}
gmp_printf("Result: %Zd\n", results[N]);
for (int i = 0; i < N + 1; i++) {
mpz_clear(results[i]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.