C 按2个条件对结构进行排序时出现分段错误
我试图分配内存,并将数据从文件d.bin(其中填充了struct record类型的数据)加载到分配的空间,然后按降序名称对数据进行排序,如果名称按降序值相同,则按降序值排序,但程序因分段错误而崩溃。我在一个单独的程序中编写了函数readfile()。这是主程序的代码C 按2个条件对结构进行排序时出现分段错误,c,C,我试图分配内存,并将数据从文件d.bin(其中填充了struct record类型的数据)加载到分配的空间,然后按降序名称对数据进行排序,如果名称按降序值相同,则按降序值排序,但程序因分段错误而崩溃。我在一个单独的程序中编写了函数readfile()。这是主程序的代码 #include <stdio.h> #include <string.h> #include "readfile.h" typedef struct{ char name[32];
#include <stdio.h>
#include <string.h>
#include "readfile.h"
typedef struct{
char name[32];
double value;
} record;
int compare_nmvm(const void* p, const void* c){
const record *p1 = *(const record **)p;
const record *p2 = *(const record **)c;
if(strcmp(p1->name, p2->name) > 0)return -1;
if(strcmp(p1->name, p2->name) < 0)return 1;
if(strcmp(p1->name, p2->name) == 0){
if(p1->value > p2->value)return -1;
if(p1->value == p2->value)return 0;
if(p1->value < p2->value)return 1;
}
int main(){
long int ld;
int i;
unsigned char* mall = readfile("d.bin", &ld);
FILE* fl = fmemopen(mall, ld, "rb");
int t = ld/sizeof(record);
record r[t];
for(i=0; i<t; i++)
fread(&r[i], sizeof(record), 1, fl);
qsort(r , t, sizeof(record), compare_nmvm);
free(mall);
fclose(fl);
return 0;
}
很抱歉发布了一大块代码,或者如果代码凌乱 如果要读取大小未知的二进制文件,实际上不需要检查整个文件的大小。您可以一次完成一个数据结构
记录温度;
记录*arr=malloc(sizeof(记录));
文件*fp=fopen(“d.bin”,“r+b”);
int i=0;
while(fread(&temp,sizeof(record),1,fp)==1){
arr=realloc(arr,sizeof(记录)*(i+1));
strcpy(arr[i].名称、临时名称);
arr[i].value=temp.value;
i++;
}
//代码如下
免费(arr);
刚刚在readfile()中看到两个错误:如果文件指针为NULL,尽管您没有退出,但可以查看文件,该文件可能不存在。如果malloc无法分配,则会得到NULL,但随后会将文件放入该NULL。为什么要尝试对f
的潜在NULL指针执行fseek
?
#include "readfile.h"
unsigned char* readfile( char* filename, long* pN ){
FILE* f = fopen(filename, "rb+");
unsigned char* mall;
long int ld;
*pN = 0;
if(f == NULL){
printf("ERROR1");
*pN = -1;
}
fseek(f, 0, SEEK_END);
if(*pN == 0){
ld = ftell(f);
*pN = ld;
fseek(f, 0, SEEK_SET);
mall = malloc(ld);
if(mall == NULL){
printf("ERROR2\n");
*pN = -2;
}
if(fread(mall, ld, 1, f) != 1){
printf("ERROR3\n");
*pN = -3;
}
}
if(*pN == -1 || *pN == -2 || *pN == -3){
free(mall);
mall = NULL;
}
fclose(f);
return mall;
}