gpt4 book ai didi

c - 试图理解这个段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:11 24 4
gpt4 key购买 nike

我试图理解为什么我在下面代码的指定行出现段错误(注释为:<<<SEGFAULT OCCURS HERE)。我写这篇文章的灵感来自 this post .

我认为这是一个内存分配问题,但考虑到即使我将事件实例的指针传递给入队函数,它仍然会出现段错误。考虑到 C 是按值传递的,即使我将 main 中的事件地址(&event 未在我发布的代码中显示)传递给入队函数,它也应该指向存在于 main 中的事件实例的地址,正确的?所以我很难理解为什么会出现段错误。

请注意,我正在寻找发生这种情况的原因,而不仅仅是解决问题。毕竟我正在努力刷新 C。 :)

相关代码:

typedef struct Event_ Event;
struct Event_ {
char action[4];
long timestamp;
char* path;
char hash[9];
Event *nextEvent; // pointer to next Event instance in Queue
};

// Enqueues newEvent into queue. Returns 1 on success, 0 otherwise.
int enqueue(Event newEvent, Event **head, Event **tail) {
if (head != NULL) {
// make the old head point to the newly inserted Event,
// and the new Event to point to NULL (nothing comes before head):
(*head) -> nextEvent = &newEvent;
newEvent.nextEvent = NULL;
} else {
// first element being added to queue.
*tail = &newEvent; //<<<SEGFAULT OCCURS HERE
}
// designate the new Event as the new head:
*head = &newEvent;

return 1;
}

// Parse line and return an Event struct.
Event parseLineIntoEvent(char* line) {
Event event = {0};
char* lineSegment;

int i = 0;
lineSegment = strtok(line, " ");
while (lineSegment != NULL) {
if (i > 3) {
printf("WARNING: input format error!\n");
break;
}
if (i == 0)
strncpy(event.action, lineSegment, sizeof(event.action)-1);
else if(i == 1)
event.timestamp = atoi(lineSegment);
else if(i == 2) {
event.path = malloc(sizeof(char) * (strlen(lineSegment) + 1));
strcpy(event.path, lineSegment);
} else if(i == 3)
strncpy(event.hash, lineSegment, sizeof(event.hash)-1);
lineSegment = strtok(NULL, " ");
i++;
} // while
return event;
} // parseLineIntoEvent()

int main (int argc, const char * argv[]) {
//...
Event **head = NULL;
Event **tail = NULL;
for (; numLines > 0; numLines--) {
char *line = getLineFromStdin(); //malloced char array being returned
printf("%s\n",line);
Event event = parseLineIntoEvent(line);
if(!enqueue(event, head, tail))
printf("An error occurred when attempting to enqueue an Event.\n");
event = dequeue(head, tail);
//...
free(event.path);
free(line);
}

return 0;
}

提前致谢!

最佳答案

Event **tail = NULL;

tailNULL,您在标记的行上取消引用它。在取消引用之前,需要使其指向 Event*:

要么

Event *ev;
Event **tail = &ev;

或者

Event** tail = malloc(sizeof(Event*));

...

free(tail);

虽然,我认为您的意思是只有一个指向 Event 的指针,并按值传递其地址:

Event *tail = NULL, *head = NULL;

...

enqueue(event, &head, &tail);

因此headtailenqueue中被修改。

关于c - 试图理解这个段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8903216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com