c++ - 为什么我的代码在本地计算机中提供 segfault/stackoverflow 并在在线编译器中正确运行?

标签 c++ ubuntu segmentation-fault

我正在解决一个竞争性编程question在代码部队上。我的 code在那里被接受,但它在我的本地计算机中出现段错误。为什么会这样?
我还尝试了其他在线编译器,例如 ideone ,它也在那里工作。
我的操作系统是 Ubuntu 20.04
我的代码:

#include <bits/stdc++.h>
using namespace std;

int M = 1000000007;

int val[1001][1001];
int n,k;
int dp(int cur,int rem)
{
    if(cur<1 || cur>k || rem<0 || rem>n)return 0;
    if(cur==1 || rem==0)return 1;

    if(val[cur][rem]==-1)
    {
        int ans=0;
        ans+=dp(cur,rem-1);
        ans%=M;
        ans+=dp(cur-1,n-rem);
        ans%=M;
        val[cur][rem]=ans;
    }

    return val[cur][rem];
    
}

void solve()
{
    cin>>n>>k;

    for(int i=0;i<=k;i++)for(int j=0;j<=n;j++)val[i][j]=-1;

    cout<<dp(k,n);
    cout<<"\n";
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int _t=1;
    cin>>_t;
    for (int i=1;i<=_t;i++)
    {
        solve();
    }
    return 0;
}

最佳答案

事实证明,我的筹码量较小。我使用了这个堆栈溢出 answer修改我的代码。这是正确的代码:

#include <sys/resource.h>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;

int M = 1000000007;

int val[1001][1001];
int n,k;
int dp(int cur,int rem)
{
    if(cur<1 || cur>k || rem<0 || rem>n)return 0;
    if(cur==1 || rem==0)return 1;

    if(val[cur][rem]==-1)
    {
        int ans=0;
        ans+=dp(cur,rem-1);
        ans%=M;
        ans+=dp(cur-1,n-rem);
        ans%=M;
        val[cur][rem]=ans;
    }

    return val[cur][rem];
    
}

void solve()
{
    cin>>n>>k;

    for(int i=0;i<=k;i++)for(int j=0;j<=n;j++)val[i][j]=-1;

    cout<<dp(k,n);
    cout<<"\n";
}

signed main()
{

    const rlim_t kStackSize = 64L * 1024L * 1024L;   // min stack size = 64 Mb
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0)
    {
        if (rl.rlim_cur < kStackSize)
        {
            rl.rlim_cur = kStackSize;
            result = setrlimit(RLIMIT_STACK, &rl);
            if (result != 0)
            {
                fprintf(stderr, "setrlimit returned result = %d\n", result);
            }
        }
    }

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int _t=1;
    cin>>_t;
    for (int i=1;i<=_t;i++)
    {
        solve();
    }
    return 0;
}

关于c++ - 为什么我的代码在本地计算机中提供 segfault/stackoverflow 并在在线编译器中正确运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67415870/

相关文章:

C++ 无效数组<T, N> 下标

c++ - 添加时选择 QListWidgetItem

ubuntu - mysqldump 恢复无法恢复某些行

c++ - 蓝牙连接失败

node.js - 在ubuntu错误消息 Node api版本上安装bcrypt

c - 只有当一个重要的指针被覆盖时,缓冲区溢出才会导致段错误吗?

python - 使用 pygame.midi 播放 midi 音符时出现段错误

c++ - 如何在多映射中将结构累积为值类型?

c++ - 使用静态链接启动 std::thread 会导致段错误

C:仅对大文件进行合并排序时出现段错误