以下程序在编译时给出以下错误:
./vpl_test:第2行:18699分段故障(核心倾倒(./solution
以下C程序有什么问题?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void sort(long *sorted, int count,long value){
int i=0;
sorted[count] = value;
if(count == 0)return;
for(i=count;i>=0;i--){
if(value<sorted[i-1])
sorted[i] = sorted[i-1];
else break;
}
sorted[i]=value;
}
int main(int argc,char *argv[]){
FILE *fp = NULL;
long sorted[1024];
long value;
int count = 0;
int i=0;
fp = fopen("brandlist.txt","r+");
//fp = fopen("brandlist.txt","w");
if(NULL == fp){
perror("fopen");
exit(0);
}
while(!feof(fp)){
fscanf(fp,"%ldn",&sorted[i]);
sort(sorted,count,value);
++count;
}
for(i=0;i<count;i++){
fprintf(fp,"%ldn",sorted[i]);
}
if(fp){
fclose(fp);
fp = NULL;
}
}
我无法再现segfault(可能是因为"幸运"或可能是因为输入错误(。
我确实遇到的问题是分类输出中的分类和奇怪的值,我相信同样的问题会导致所有行为不端,包括您的情况下的segfault。
这是您的代码的评论版本,从出色的评论中拾取,并添加(许多(在字符串而不是整数上工作的必要更改。
(允许我这个小小的咆哮:它确实节省了很多时间来提供实际的样本输入。(
它确实没有segfault(至少对我来说不是(,没有错过,也没有奇怪的价值观。输出(即输入文件的新内容(:
Damro
Duriyan
Evoks
Godrej
Luxxe
Nilkamal
Wipro
Zuari
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char brandname[20];
void sort(brandname *sorted, int count, brandname *value){
int i=0;
strncpy((char*)sorted[count], (char*)value, sizeof(brandname));
if(count == 0) return;
// picking up input by BLUEPIXY;
// this probably prevents the segfault,
// it definitly prevents strange values
// appearing in the sorted result
for(i=count;i>0;i--)
{
if(0>strncmp((char*)value, (char*)sorted[i-1],sizeof(brandname)))
strncpy( (char*)sorted[i], (char*)sorted[i-1], sizeof(brandname));
else break;
}
strncpy((char*)sorted[i], (char*)value, sizeof(brandname));
}
int main(int argc,char *argv[]){
FILE *fp = NULL;
brandname sorted[1024];
brandname value;
int count = 0;
int i=0;
fp = fopen("brandlist.txt","r+");
//fp = fopen("brandlist.txt","w");
if(NULL == fp){
perror("fopen");
exit(0);
}
// picking up input from cooments on feof
// but also use the increasing "count"
// instead of unchanging "i"
while(1==fscanf(fp,"%s", value))
{
// use the read value inside "sorted[count]"
sort(sorted, count, &value);
++count;
}
// do not append sorted to input
rewind(fp);
for(i=0;i<count;i++){
fprintf(fp,"%sn",sorted[i]);
}
if(fp){
fclose(fp);
fp = NULL;
}
// avoid a warning
return 0;
}