【发布时间】:2015-01-17 10:33:39
【问题描述】:
我在尝试初始化嵌套结构时遇到问题。
在编译时,没有错误,但在执行时,我遇到了段错误。 在 valgrind 中,我得到了
> Invalid read of size 8 at 0x402175: new_animal
> Address 0x38 is not stack'd, malloc'd or (recently) free'd
代码如下:
void new_animal(int i, int j, int species){
struct animal * a;
if (array[i][j]==NULL)
{
a = malloc(sizeof(struct animal));
assert (a);
a->espece=espece;
if(array[i][j]->player==NULL)
{
a->player->id_fisherman=0;
strcpy(a->player->Name,"N"); //I want it set to NULL.
}
}
grille[i][j] = a;
}
这是两个结构:
struct fisherman {
int id_fisherman;
char Name[10];
};
struct animal {
int species;
struct fisherman* player;
};
在我添加渔夫之前,它运行良好。不知道是内存分配的原因,还是我在初始化的时候。
【问题讨论】:
-
这与“嵌套”结构无关。
-
两者之一:或者您将
player字段声明为仅struct fisherman(没有*),或者您对其执行另一个malloc(),或者将指针初始化为有效(某物的地址)。