簡體   English   中英

查找細分錯誤

[英]Finding a segmentation fault

我只需要另一雙眼睛來幫助我指出我肯定犯的一個愚蠢的錯誤。

結構和原型:

typedef struct node {
    int data;
    struct node *next;
} Node;

Node *orderedInsert(Node *p, int newval);
/* Allocates a new Node with data value newval
   and inserts into the ordered list with 
   first node pointer p in such a way that the
   data values in the modified list are in 
   nondecreasing order as the list is traversed.
*/

功能:

#include "orderedList.h"
#include <stdio.h>
#include <stdlib.h>

Node *orderedInsert(Node *p, int newval){
       struct node* new = NULL
       new = malloc(sizeof(struct node));
       struct node* last = p;

       while(1){
          if (p == NULL){
             if (last == p){
                return 1;
             }
             new->data = newval;
             new->next = NULL;
             break;
          }
          if ((last->data <= newval) && (p->data >= newval)){
             new->data = newval;
             new->next = p;
             break;
          }
       }
       return 0;
    }

使用任何參數調用orderedInsert時出現分段錯誤。

我不認為該函數本身存在段錯誤,可能是在調用代碼中沒有顯示給我們。 盡管這里有幾個明顯的錯誤。 最明顯的是,它實際上並未插入任何內容。 此函數創建了新節點,但是它絕不會以任何方式更改現有列表,因此該節點是孤立的。 其次,它被聲明為返回指針,但是它返回0或1。這不會分段,但是如果調用方期望指針並以這種方式取消引用,則可以。

因此,根據您的反饋,您的問題是,不是從orderedInsert返回Node *orderedInsert返回10 ,如果調用代碼嘗試取消引用,則將導致seg fault 正如Lee指出的那樣,還有其他問題,例如您實際上並未正確插入新節點。

您在struct node * “新”指針的聲明中錯過了分號。 您的方法實現由於返回值而容易發生內存泄漏。

實際上,在談論該方法時,很明顯,它永遠不會產生分段錯誤。 在大多數情況下,此方法將循環運行,直到您關閉正在運行該方法的進程為止。

此例程有三個“用例”:

  1. 調用orderedInsert(NULL,/* whatever */)並以0x00000001地址獲取Node * ;
  2. 在堆棧或堆上分配struct node類型變量的空間,然后調用orderedInsert(/* newly allocated variable pointer */,/* value */)但請確保新分配的變量的->data等於您的value傳進去。 對於此實例,您的方法返回空指針。 期;
  3. 調用orderedInsert(/* Non-null */,/* not equal to "data" */)並始終享受代碼循環的樂趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM