2012-02-10 111 views
1

代碼如下,看起來好像沒什麼問題。我的GCC犯規找到alloc.h分段錯誤,未分配內存

print(node *q) 
    39 { 
    40  node *p=q; 
    41    do 
    42  { 
    43   printf("%d",p->n); 
    44   if(p->ptr != NULL) 
    45   p=p->ptr; 
    46   else 

(GDB)PP $ 1 =(節點*)爲0x0

在哪裏內存分配代碼

if(p== NULL) 
    { 
      p=(node *)malloc(sizeof(node)); 
      if(p== NULL) 
        printf("The malloc failed\n"); 
      p->n=num; 
      p->ptr=NULL; 
    } 

當我運行這調試器沒有malloc失敗的消息。

任何人都可以幫忙。 問候

Sraddha

add(node **q) 
    { 
     node *p=*q; 
     int num; 
     printf("Enter the number you want to add"); 
     scanf("%d", &num); 
     if(p== NULL) 
     { 
      p=(node *)malloc(sizeof(node)); 
      if(p== NULL) 
        printf("The malloc failed\n"); 
      p->n=num; 
      p->ptr=NULL; 
     } 
    } 
+2

是'在p'傳遞給分配函數作爲參數(類型爲'節點*')的任何機會? – Mat 2012-02-10 11:24:05

+0

你可以編輯你的帖子來顯示該循環的其餘部分,並說出segv的發生地點嗎?而且,正如Mat所暗示的那樣,也顯示了整個分配功能。 – Useless 2012-02-10 11:24:57

+0

是p被聲明爲節點* p; – sraddhaj 2012-02-10 11:28:15

回答

0

除了由hmjd的回答提出的問題,您可能希望考慮一個不同的程序設計。你已經使功能做了三件完全不同的事情:與用戶交互,分配內存和實際算法。這個程序設計是導致錯誤的真正罪魁禍首。

相反,你可能要考慮一個更面向對象的方法:

int prompt_user (void) // this function interacts with the user ("GUI") 
{ 
    int num; 
    printf("Enter the number you want to add"); 
    scanf("%d", &num); 
    getchar(); // discard line feed character from stdin 

    return num; 
} 

void init_node (node* new_node, int num) 
{ 
    new_node->n = num; 
    new_node->ptr = NULL; 
} 


// this code is the caller: 
{ 
    node* q = NULL; 

    ... 

    int num = prompt_user(); 

    if(q == NULL) 
    { 
    q = malloc(sizeof(node)); 
    if(q == NULL) 
    { 
     // error handling 
    } 
    } 

    init_node(q, num); 

    ... 

    free(q); 
} 
+0

謝謝Lundin這是一個好方法。 – sraddhaj 2012-02-10 23:06:51

5

您需要分配到*qadd()功能,而不是本地p

add(node **q) 
{ 
    int num; 
    printf("Enter the number you want to add"); 
    scanf("%d", &num); 
    if(*q == NULL) 
    { 
     *q = malloc(sizeof(node)); /* no need to cast return value. */ 

     /* Corrected if logic to not access failed malloc. */ 
     if(*q == NULL) 
     { 
      printf("The malloc failed\n"); 
     } 
     else 
     { 
      *q->n=num; 
      *q->ptr=NULL; 
     } 
    } 
} 
+0

是的,我明白了。謝謝hmjd。我會試試這個。 – sraddhaj 2012-02-10 11:41:49

+0

在這個答案中有關malloc的評論是重要的,[閱讀此](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc)。 – Lundin 2012-02-10 13:37:28

+0

@sraddhaj,這是否解決了它? – hmjd 2012-02-19 09:47:30