【发布时间】:2018-03-12 17:12:06
【问题描述】:
我有一个函数应该从文件中读取,创建数据结构并返回。该功能有效,就在返回线之前,一切看起来都很好,结构看起来还不错。但随后,该功能失败 -
“运行时检查失败 #2 - 变量‘输出’周围的堆栈已损坏。”
该文件包含有关发电站和城市的信息。(输出、位置、名称等) 有些行是城市,有些是发电站,与行中的最后一个整数(或缺少)不同。如果它存在(我们称他为 X),这条线是一个发电站,接下来的 X 线是与之相连的城市。
这个函数。应该创建指向车站指针(车站**)的指针,所有城市都连接到每个车站。
station** read_from_file(FILE *file , station **power_grid){
int output , cities_connected ,i, counter = 0 ,j =0;
double x , y;
char name[256] = {0};
station *st;
while (fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output, &x, &y, &cities_connected) != EOF){
counter++;
for( i = 0; i < cities_connected; i++){
fscanf(file , "%*c%[^\"]%*c%lf%lf%lf\n" , name , &output , &x ,&y);
}
}
power_grid = (station **)malloc(sizeof(station *)* counter);
rewind(file);
while (fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output, &x, &y, &cities_connected) != EOF)
{
st = (station *)malloc(sizeof(station));
st->capacity = output;
st->cities_list = NULL;
st->num_of_cities = cities_connected;
st->name = (char *)malloc(strlen(name));
strcpy(st->name , name);
st->location[0] = x;
st->location[1] = y;
st->cities_list = (city **)malloc(sizeof(city *)*cities_connected);
for( i = 0; i < cities_connected; i++){
fscanf(file , "%*c%[^\"]%*c%lf%lf%lf\n" , name , &output , &x ,&y);
st->cities_list[i] = (city *)malloc(sizeof(city));
st->cities_list[i]->consumption = output;
st->cities_list[i]->location[0] = x;
st->cities_list[i]->location[1] = y;
st->cities_list[i]->name = (char *)malloc(strlen(name)+1);
strcpy(st->cities_list[i]->name , name);
}
power_grid[j] = st;
j++;
}
fclose(file);
return;
}
车站和城市结构-
typedef struct city {
char * name;
double location[2];
double consumption;
}city;
typedef struct station {
char * name;
double location[2];
city ** cities_list;
int num_of_cities;
double capacity;
}station;
测试文件 - here
【问题讨论】:
-
fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output,:类型不匹配。output的类型是int。 -
st->name = (char *)malloc(strlen(name));-->st->name = (char *)malloc(strlen(name)+1); -
@BLUEPIXY 谢谢!那行得通!问题在于输出的类型。 (还在 st->name malloc 上添加了一个)
标签: c string memory-management dynamic-memory-allocation stack-corruption