1

我的程序有一些列表处理函数,在我添加 reverseLinkedList 函数之前一切正常。我观察到有一个段。错误错误,后来我通过添加 printf() “解决”错误想通了,但我不知道为什么。

这是代码片段:

NODE *list_B;
void functionA();

int main ( )
{
..


   functionA();
   printf("O.o\n");// <=== if I add this line, the seg. fault is gone. Without it, I got the error
   printSummary(); //this is just printing out whatever is in list_B
}
void functionA()
{
   list_B = reverseLinkedList(list_B);
}

NODE* reverseLinkedList(NODE *head) //this is implemented in other head file.
{
    NODE *current = NULL;
    NODE *temp;

    while(head != NULL)
    {
        temp = head;
        head = head->next;
        temp->next = current;
        current = temp;
    }

    return current;
}
4

2 回答 2

6

You've figured out that printf() doesn't actually solve the problem in your code, it just masks the problem so you don't get a segmentation fault.

The segmentation fault is a good thing, because it helps you find the error in your code. When you add printf(), the error is still there but the segmentation fault is gone... so it's harder to find the error.

Memory errors in C programs can result in very strange behavior. Basically, anything can happen if your program has a memory error, and in this particular case what actually happens depends on whether that printf() call gets executed. It would probably take a bit of sleuthing to figure out exactly what is going on here, but it is possible (for example) that some of your code depends on uninitialized memory, and printf() leaves behind some values in that memory that cause your other code to proceed harmlessly.

There are a number of different tools you can use to diagnose these problems.

  1. Since your code gets a segmentation fault, you can hook up a debugger and see where the crash is. The incorrect code might crash, or the crash might happen long after the incorrect code has executed.

  2. Valgrind will often tell you which parts of your program rely on uninitialized values, which are a common source of this kind of crash.

  3. Mudflap (compile with gcc -fmudflap) will also find some of these errors. Mudflap and Valgrind have a lot of overlap, but sometimes one of them will find an error that the other one doesn't.

于 2013-05-14T03:23:39.820 回答
2

Calling printf changes the values on the stack. If the functions after the printf do not initialize their local variables properly, this results in different behaviour including the printf() or not.

You seem to be comparing stock_name before it is set (with malloc()). Is that a global variable?

于 2013-05-14T03:23:08.870 回答