【发布时间】:2021-02-23 17:22:46
【问题描述】:
在下面的代码中,我试图创建一个函数 maketudernts()。它接受一个字符串并将对象放入数组中并返回它。
但是,我收到以下错误
a.out: malloc.c:2374: sysmalloc: 断言 `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2 ])) - __builtin_offsetof (struct mallo c_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+( (2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & 页面掩码) == 0)' 失败。 中止(核心转储)
我唯一能想到的是 字符串 str3 = malloc(sizeof(char)*i); 是导致它的线。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* String;
void stringMalloc(String str, int size);
String fileToString(FILE * file);
void freeString(String str);
struct Point2D{
double x;
double y;
};
struct busRote{
struct Point2D * point;
String name;
};
struct Student{
struct Point2D point;
String name;
struct busRote rote;
int stop;
};
void setPoint(struct Point2D * i , double x, double y){
(*i).x =x;
(*i).y = y;
}
void* makestudernts(String str){
String str1 = str;
String str2 = strchr(str1, ' ' );
int count = 0;
while(strchr(str1, '\n') != NULL){
count++;
str1 = strchr(str1, '\n') +1;
}
struct Student * arr = malloc( sizeof(struct Student*) * count);
str1 = str;
str2 = strchr(str1, ' ' );
for(int j = 0; j < count; j++){
double x = strtod(str1, &str2);
str1 = str2;
str2 = strchr(str1, ' ' );
double y = strtod(str1, &str2);
str1 = str2;
int i = 0;
i = 5;
i = strlen(str2);
if( (strchr(str2, '\n') - str2) < i ){
i= strchr(str2, '\n') - str2;
}
str2 = strchr(str2, '\n');
String str3 = malloc(sizeof(char)*i);
strncpy(str3, str1, i);
str1 = str2;
struct Point2D point;
setPoint(&point, x,y);
struct Student student;
student.point = point;
student.name = str3;
arr[j] = student;
}printf("%s", arr[0].name);
return arr;
}
int main(int argi, String argv[]){
if(argi <3){
printf("not enof files");
}else{
FILE* studentFile;
FILE* busFile;
studentFile = fopen (argv[1], "r");
busFile = fopen (argv[2], "r");
if (studentFile == NULL || busFile == NULL){
printf("files not found");
}else{
String studentString;
String busString;
studentString = fileToString(studentFile);
busString = fileToString(busFile);
struct Student * arr= makestudernts(studentString);
freeString(studentString);
freeString(busString);
fclose(studentFile);
fclose(busFile);
}
}
}
String fileToString(FILE * file){
char ch = fgetc( file );
int count = 0;
while(ch != EOF){
count++;
ch = fgetc(file);
}
String string = malloc(sizeof(char) * count);
rewind(file);
for(int i = 0; i < count; i++){
string[i] = fgetc(file);
}
return string;
}
void freeString(String str){
free(str);
}
【问题讨论】:
-
请发布minimal reproducible example,包括
main函数以及编译和运行代码所需的所有其他内容,而无需猜测要填写什么。
标签: c