【问题标题】:Tricky seg fault in CC中棘手的段错误
【发布时间】:2014-12-20 22:51:19
【问题描述】:

我正在尝试为我的大学作业运行一个 C 项目,但在以下代码段中的“while (current->next != NULL) {”行中遇到了段错误:

FILE* f = fileOpen("test.txt");
if (f != NULL){
    functionList = fileReadToMemory(f, &graphParams);//functionList is a pointer to the first value of the linked list it creates
    current = functionList;

    while (current->next != NULL) {
        printf("%d %d %d %s", current->red, current->green, current->blue, current->expression);//Prints value of linked list
        current = current -> next;
    }
}

gdb给我的错误如下:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000000003a
0x0000000100000b30 in main () at main.c:23
23          while (current->next != NULL) {

我做错了什么?

提前致谢!

【问题讨论】:

    标签: c pointers segmentation-fault gdb fault


    【解决方案1】:

    你需要做的

    while (current != NULL) 
    

    而不是

    current->next != NULL 
    

    因为列表中的最后一个元素会导致段错误。

    【讨论】:

    • .. 如果返回的 functionList 恰好是 NULL,这几乎是一个副作用,那么它也将正常工作。
    • 是的,在这种情况下,链表的头部为空,所以 while (current != NULL) 可以解释为“链表是否还有元素?”
    • 是的,在这种情况下,链表的头部为空。如此有效,NULL 值仍然是一个有效的链表,只是它是一个空链表。所以 while (current != NULL) 可以解释为“链表还有元素吗?”,它适用于任何大小的链表,甚至是 0。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多