gpt4 book ai didi

c - 在代码片段 1 中发现段错误,但在代码片段 2 中未发现,两者的实现方式类似

转载 作者:行者123 更新时间:2023-11-30 20:53:49 26 4
gpt4 key购买 nike

我在以下代码 1 的第 1 行遇到段错误。代码片段2中使用malloc函数编写了相同的代码,但代码2中没有发现此类错误。您能告诉我背后可能的原因吗?

我知道我正在尝试访问 code1 中未初始化的内存位置 - 这可能是 seg'n 错误的原因,但我的问题是,如果这是真的,那么为什么在 code2 中没有观察到错误。

谢谢!

代码片段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];
}

最佳答案

I know that i am trying to access a memory location in code1 which is not initialized- this could be the reason for seg'n fault but my question is, if this is true, then why is no error observed in code2.

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

关于c - 在代码片段 1 中发现段错误,但在代码片段 2 中未发现,两者的实现方式类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45117486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com