我编写了以下内容,用于对从stdin中读入C中的N个整数进行排序,使用插入排序对它们进行排序,并计算为SPOJ排序所需的交换次数问题:http://www.spoj.com/problems/CODESPTB/在插入排序中计算移位时出现Seg错误 - C
我的代码适用于给定的示例输入,我也测试过较大的整数集f较大的值,一切似乎都正常工作。但是,当我在SPOJ的在线裁判上运行它时,它在运行时会出现分段错误。不幸的是,SPOJ上的问题的创造者并没有将复习失败作为一种选择。我不知道导致seg故障的原因。我的代码中的任何内容都会跳出来指出可能导致它的原因?
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFF 100
int main(int argc, char *argv[]){
char buffer[MAX_BUFF];
char *long_str;
int T, N;
long *a;
printf("Enter a T value between 1 and 5 inclusive: ");
bzero(buffer, MAX_BUFF);
fgets(buffer, MAX_BUFF - 1, stdin);
T = atoi(buffer);
if(T<1 || T>5){
printf("Error: T must be 1<=T<=5\n");
exit(0);
}
const char delim[2] = " ";
char *token;
while(T > 0){
printf("Enter a N value between 1 and 100000 inclusive: ");
bzero(buffer,MAX_BUFF);
fgets(buffer, MAX_BUFF-1, stdin);
N = atoi(buffer);
if(N<1 || N>100000){
printf("Error: N must be 1<=N<=100000\n");
exit(0);
}
int current_size = 0;
long_str = malloc(MAX_BUFF);
current_size = MAX_BUFF;
printf("Enter N integers separated by spaces: ");
if(long_str != NULL){
int c = EOF;
unsigned int i = 0;
while((c = getchar()) != '\n' && c != EOF){
long_str[i++]=(char)c;
if(i==current_size){
current_size = i + MAX_BUFF;
long_str = realloc(long_str, current_size);
}
}
long_str[i] = '\0';
}
token = strtok(long_str, delim);
a[0]=atol(token);
int i = 1;
while (token != NULL && i < N) {
token = strtok(NULL, delim);
if(token == NULL){
printf("Error, not enough ints specified, terminating\n");
exit(0);
}
a[i] = atol(token);
i++;
}
free(long_str);
int j, tmp, count;
count = 0;
for(i=1; i<N; i++){
j=i;
while(j>0 && a[j]<a[j-1]){
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
j--;
count++;
}
}
T--;
}
}
作为一个堆栈溢出的新用户,如果你打算低估我的问题,你至少可以解释为什么? – jgriff 2014-09-26 16:34:54