我试图提交此代码以解决hackerearth的问题而且我正在接受
这个SIGSEGV Runtime error
。我读到了这个错误但我无法使我的代码工作。有人说它是由于无效的内存引用,数组的动态初始化或数组索引超出限制而发生的。
#include <stdio.h>
long long int f(long long int);
long long int gcd(long long int,long long int);
int main(){
long long int n,q,i;
scanf("%lld",&n);
long long int a[n];
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
}
scanf("%lld",&q);
while(q--){
char ch;
long long int x,y,sum=0;
scanf("%c%lld%lld",&ch,&x,&y);
if(ch == 'U'){
a[x] = y;
}
else if(ch == 'C'){
for(i=x;i<=y;i++){
sum = (sum + f(a[i]))%1000000007;
}
}
printf("%lld\n",sum);
}
return 0;
}
long long int f(long long int t){
long long int i;
long long int res;
for(i=1;i<=t;i++){
res = (res + gcd(i,t))%1000000007;
}
return res;
}
long long int gcd(long long int x,long long int t){
int i;
long long int divisor=1;
for(i=1;i<=x;i++){
if(x%i == 0 && t%i == 0){
divisor = i;
}
}
return divisor;
}
答案 0 :(得分:1)
一个明显的错误:
long long int a[n];
for(i=1;i<=n;i++){ // <-- will cause buffer overrun on last iteration
scanf("%lld", a[i]); // <-- need address of argument
在循环的最后一次迭代中,您正在访问a[i]
i == n
,这是scanf
时的缓冲区溢出。此外,您的 long long int a[n];
for(i=1;i<n;i++){
scanf("%lld", &a[i]);
要求传递地址。
循环应该是:
long long int a[n+1];
for(i=1;i<=n;i++){
scanf("%lld", &a[i]);
或者如果你真的想使用假的基于1的数组(我真的不建议这样做,因为我已经看过很多次代码中某处有一个一个错误的错误),你会这样做这样:
import javax.inject.Inject;
public class ThreadA implements Runnable {
@Inject
private MySignal sharedSignal;
@Override
public void run() {
while (!sharedSignal.hasDataToProcess()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Finished");
};
}
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
@Named("sharedSignal")
@ApplicationScoped
public class MySignal {
protected boolean hasDataToProcess = false;
public synchronized boolean hasDataToProcess() {
return this.hasDataToProcess;
}
public synchronized void setHasDataToProcess(boolean hasData) {
this.hasDataToProcess = hasData;
}
}
public class Main {
public static void main(String[] args) {
Thread a = new Thread(new ThreadA());
a.start();
}
}