为什么我在 Leetcode 上遇到运行时错误?

问题描述 投票:0回答:1

我在 leetcode 上解决问题(204. Count Primes)时遇到此错误

AddressSanitizer:DEADLYSIGNAL
=================================================================
==22==ERROR: AddressSanitizer: stack-overflow on address 0x7ffcaa1c28a0 (pc 0x55dc763f8828 bp 0x7ffcc7e99220 sp 0x7ffcaa1c2860 T0)
    #1 0x7f7f641dcd8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
    #2 0x7f7f641dce3f  (/lib/x86_64-linux-gnu/libc.so.6+0x29e3f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
==22==ABORTING
    class Solution {
    public:
    bool status[100000000];
    int prime[100000000];
    int ct=0;
    void sieve()
    {
    int i,j,n=5000000;
    status[1]=1;
    for(i=4; i<=n; i+=2) status[i]=1;
    for(i=3; i<=sqrt(n); i+=2)
    {
    if(status[i]==0)
    {
        for(j=i*i; j<=n; j+=i)
            status[j]=1;
    }
    }
    for(i=1; i<=n; i++)
    {
    if(status[i]==0)
    {

       prime[ct++]=i;
    }
    }
    }
    int lower_bnd(int key)
    {
    int b=0,e=ct-1, mid;
    while(b<=e)
    {

    mid=(b+e)/2;
    if(key==prime[mid])
    {

        e=mid-1;
    }
    else if(prime[mid]<key) {
        b=mid+1;
    }
    else if(prime[mid]>key)
    {

        e=mid-1;
    }
    }
    return b-1;

    }
    int countPrimes(int n) {
    sieve();
    return lower_bnd(n)+1;
    }
    };
c++ c runtime-error c++14
1个回答
0
投票

你的类太大了,你不能使用该类的实例作为局部变量。

  bool status[100000000];
  int prime[100000000];

试试这个,这不是一个优雅的解决方案,但它可能会完成工作。

  static bool status[100000000];
  static int prime[100000000];
© www.soinside.com 2019 - 2024. All rights reserved.