2017-07-15 3 views
-3

以下のコード1のLine-Line1でセグメント違反が発生しています。同じコードがコードスニペット2のmalloc関数を使用して記述されていますが、コード2にこのようなエラーはありません。 その背後にある理由を教えてください。コードスニペット1でセグメント違反が見つかりましたが、コードスニペット2ではなく、両方とも同様の方法で実装されています

私は、初期化されていないcode1のメモリ位置にアクセスしようとしていることを知っています - これはseg'nフォルトの理由である可能性がありますが、私の質問は、これが真であれば、 。

ありがとうございます!

コードスニペット1:

struct tnode 
    { 
     int d; 
     struct tnode *left; 
     struct tnode *right; 
    }; 

    void printLOT(struct tnode *n) 

    { 
    tnode *q[20]; 
    int front=0, rear=-1; 

    if(n==NULL) 
    { 
     cout<<"no element in tree."; 
     return; 
    } 

    struct tnode *tmp=n; 
    while(tmp) 
    { 
     cout<<tmp->d<<" "; //*Line1* 
     if(tmp->left!=NULL) 
     { 
      q[++rear]=tmp->left; 
     } 
     if(tmp->right!=NULL) 
     { 
      q[++rear]=tmp->right; 
     } 
     tmp=q[front++]; 

    } 
    return; 
} 

コードスニペット2:

void printLevelOrder(struct node* root) 
{ 
    int rear, front; 
    struct node **queue = createQueue(&front, &rear); 
    struct node *temp_node = root; 

    while (temp_node) 
    { 
     printf("%d ", temp_node->data); 

     /*Enqueue left child */ 
     if (temp_node->left) 
      enQueue(queue, &rear, temp_node->left); 

     /*Enqueue right child */ 
     if (temp_node->right) 
      enQueue(queue, &rear, temp_node->right); 

     /*Dequeue node and make it temp_node*/ 
     temp_node = deQueue(queue, &front); 
    } 
} 

/*UTILITY FUNCTIONS*/ 
struct node** createQueue(int *front, int *rear) 
{ 
    struct node **queue = 
     (struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE); 

    *front = *rear = 0; 
    return queue; 
} 

void enQueue(struct node **queue, int *rear, struct node *new_node) 
{ 
    queue[*rear] = new_node; 
    (*rear)++; 
} 

struct node *deQueue(struct node **queue, int *front) 
{ 
    (*front)++; 
    return queue[*front - 1]; 
} 
+8

*未定義の動作*はセグメンテーションを保証しません。 – UnholySheep

+0

'cout < d <<" "; // * Line1 * 'はコンパイルされません。 – chux

答えて

2

私は、これは可能性がinitialized-されていないCODE1のメモリ場所にアクセスしようとしていますことを知っていますなぜseg'nの断層の理由が、私の質問は、これが本当であれば、なぜコード2でエラーが観察されないということです。

初期化されていないメモリの読み込みには、未定義の動作があるためです。

関連する問題