Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在代码段1中发现分段错误,但在代码段2中未发现分段错误,而两者的实现方式类似_C_Segmentation Fault - Fatal编程技术网

C 在代码段1中发现分段错误,但在代码段2中未发现分段错误,而两者的实现方式类似

C 在代码段1中发现分段错误,但在代码段2中未发现分段错误,而两者的实现方式类似,c,segmentation-fault,C,Segmentation Fault,我在下面代码1的第1行遇到分段错误。在代码段2中使用malloc函数编写了相同的代码,但在代码2中没有发现这样的错误。 你能告诉我可能的原因吗 我知道我试图访问代码1中未初始化的内存位置-这可能是seg'n故障的原因,但我的问题是,如果这是真的,那么为什么代码2中没有观察到错误 谢谢 代码片段1: struct tnode { int d; struct tnode *left; struct tnode *right; }

我在下面代码1的第1行遇到分段错误。在代码段2中使用malloc函数编写了相同的代码,但在代码2中没有发现这样的错误。 你能告诉我可能的原因吗

我知道我试图访问代码1中未初始化的内存位置-这可能是seg'n故障的原因,但我的问题是,如果这是真的,那么为什么代码2中没有观察到错误

谢谢

代码片段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;
}
我知道我试图访问代码1中未初始化的内存位置-这可能是seg'n故障的原因,但我的问题是,如果这是真的,那么为什么代码2中没有观察到错误

因为读取未初始化的内存具有未定义的行为。

未定义的行为不能保证segfault.cout
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];
}