我想了解为什么我在下面的代码的指定行(出现于:<<<SEGFAULT OCCURS HERE
)中获得段错误。我从this post获得了很多灵感。试图了解此分段错误
我认为这是一个内存分配问题,但考虑到即使我将一个Event实例的指针传递给enqueue函数,它仍然存在段错误。考虑到C是按值传递的,即使当我将main中的事件地址(&event
未显示在此处的代码中)传递给enqueue函数时,它应该指向存在于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;
}
提前感谢!
'enqueue'函数被打破。您通过值传递'newEvent',这不会修改您传递的事件。 – pmr 2012-01-17 23:39:27