【发布时间】:2017-05-20 12:25:30
【问题描述】:
这让我发疯了,我已经完成了我的作业,但由于某种原因在这里
for (int i = 0; i < room->num_of_challenges; i++) { // need a check
if (strcmp(room_to_enter, room->challenges[i].challenge->name) == 0) {
room->challenges[i].start_time = start_time;
room->challenges[i].visitor = malloc(sizeof(room->challenges[i].visitor));
room->challenges[i].visitor->current_challenge = malloc(sizeof(room->challenges[i].visitor->current_challenge));
*room->challenges[i].visitor->current_challenge = room->challenges[i];
*room->challenges[i].visitor->room_name = NULL;
*room->challenges[i].visitor->room_name = malloc(strlen(room_to_enter)+1);
strcpy(*room->challenges[i].visitor->room_name, room_to_enter);
inc_num_visits(room->challenges[i].challenge);
}
}
此时程序由于某种原因崩溃了:
*room->challenges[i].visitor->room_name = malloc(strlen(room_to_enter)+1);
这是一个3页的代码,每个页都有标题,每页大约300行,所以我不能全部发布,这里也是结构:
struct SChallengeActivity;
typedef struct SVisitor
{
char *visitor_name;
int visitor_id;
char **room_name;
struct SChallengeActivity *current_challenge;
} Visitor;
typedef struct SChallengeActivity
{
Challenge *challenge;
Visitor *visitor;
int start_time;
} ChallengeActivity;
typedef struct SChallengeRoom
{
char *name;
int num_of_challenges;
ChallengeActivity *challenges;
} ChallengeRoom;
我们无法编辑结构,因为它是由作业给出的,问题是我试图将这一行设置为 NULL,如下所示:
*room->challenges[i].visitor->room_name = NULL;
它仍然在那一行崩溃,由于某种原因它无法到达结构中的那个字段。 注意:忽略编码,我知道我应该在每行之后检查 malloc,但现在我想让它工作,我整晚都在努力让它工作,但我做不到,有什么帮助吗? 谢谢
【问题讨论】:
-
好吧,“房间”不好,“我”不好或“访客”不好。你的调试器说什么?
-
room->challenges[i].visitor = malloc(sizeof(room->challenges[i].visitor));这看起来不对。您可能分配的是指针的大小,而不是结构。
标签: c pointers struct null crash