2015-11-21 173 views
-7

當我運行我的程序時我得到這個錯誤任何人都可以解釋這是什麼錯誤?運行程序時出錯?

*** Error in `./a.out': double free or corruption (out): 0x00000000022030e0 *** 
    Aborted (core dumped) 

這裏是我的代碼

#include<stdio.h> 
#include<algorithm> 
#include<queue> 
#include<string> 
#include<string.h> 
#include<iostream> 
using namespace std; 
struct node{ 
    char data; 
    int freq; 
    struct node* left; 
    struct node* right; 
    }; 
struct my{ 
    bool operator()(struct node* n1,struct node* n2){ 
     return n1->freq<=n2->freq; 
    } 
}; 
void print(struct node* root,char n[]) 
{ 
    int i; 
    if ((root->left==NULL)&&(root->right==NULL)) 
    { 
     cout<<n<<"\n"; 
     //printf("%s\n",n); 
    } 
    if(root->left!=NULL) 
    { 
     int k=strlen(n); 
     n[k]='0'; 
     n[k+1]='\0'; 
     print(root->left,n); 
     n[k]='\0'; 
    } 
    if(root->right!=NULL) 
    { 
       int k=strlen(n); 
       n[k]='1'; 
       n[k+1]='\0'; 
       print(root->right,n); 
       n[k]='\0'; 
    } 
    return ; 
} 
int main() 
{ 
    int a[5]={1,1,2,3,5}; 
// priority_queue<struct node , vector<struct node>,my> q; 
    priority_queue<node*,vector<node*>,my> q; 
    for(int i=0;i<5;i++) 
    { 
     struct node* s=new node; 
     s->data=i; 
     s->freq=a[i]; 
     s->left=NULL; 
     s->right=NULL; 
     q.push(s); 
    } 
    while(q.size()>=1) 
    { 
     struct node* a=q.top(); 
     q.pop(); 
     struct node* b=q.top(); 
     q.pop(); 
     struct node* c=new node; 
     c->freq=a->freq+b->freq; 
     c->left=a; 
     c->right=b; 
     q.push(c); 
    } 
    printf("0"); 
    char n[100]; 
    n[0]='\0'; 
    struct node* d=q.top(); 
    print(d,n); 
    return 0; 
} 

它顯示了執行最後一行之後錯誤。 *錯誤在./a.out': double free or corruption (out): 0x00000000015f50e0 *** Aborted (core dumped) *** Error in ./a.out「:雙重釋放或腐敗(出):0x00000000015f50e0 * 中止(核心轉儲)

+1

這是運行程序時發生的錯誤,而不是編譯時。 – interjay

+0

是的,你知道這是爲什麼嗎? –

+1

正如錯誤所述,無論是兩次釋放相同的內存,還是有一些內存損壞。沒有代碼就難以說更多。 – interjay

回答

1

這個條件while(q.size()>=1)不可能是正確的。當你總是push一個元素在循環隊列,大小永遠不能低於1

然而,當大小 1,你還是儘量pop 2個元素從隊列中添加一個新的前。這看起來像堆腐敗,而不是雙倍免費。

+0

感謝您的幫助 –

0

這是不是一個錯誤的編譯。在編譯並鏈接它之後,運行該程序時出錯。

原因如果您的程序源中存在缺陷。

典型原因包括

  • 調用free()兩次對同一指針(在C更常見,但確實發生在C++)。
  • 在相同的指針上使用operator delete兩次。
  • 調用上的指針這是操作員new
  • 的結果使用由malloc()

的可能原因的列表推移和返回上的指針的任何形式的操作員deletefree()。實際上,從概念上講,任何C++標準所稱的未定義行爲都會導致這種症狀。但未定義的行爲可能會有任何結果。

至於你的代碼中的具體原因 - 沒有人會猜測,除非你顯示代碼。

+0

我給出了我的代碼 –

+1

當我開始起草我的答覆時,你還沒有。 – Peter