简体   繁体   English

链表节点上的分段错误

[英]segmentation fault on linked list node

I thought about linked list, but there are segmentation fault. 我想到了链表,但是有分段错误。 But I don't know, why this code has memory leak... 但我不知道,为什么这段代码有内存泄漏...

I just tried 我刚试过

codeblock said, ptr = next; 代码块说,ptr = next; <- this part has segmentation fault. <-这部分有分割错误。

if(head == NULL)
        {
            head = new Nodes;
            head->r_data = data1;
            head->u_data = data2;
            head->r_node = NULL;
            head->u_node = NULL;
        }
        else
        {
            Nodes *ptr;
            ptr = head;
            Nodes *next;
            next = head->r_node;
            while(ptr != NULL)
            {
                if(ptr->r_data == data1)
                {
                    next = ptr->u_node;
                    while(ptr != NULL)
                    {
                        if(ptr->u_data < data2)
                        {
                            ptr = next;
                            next = ptr->u_node;
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;
                }
                else if(ptr->r_data < data1)
                {
                    ptr = next;
                    next = ptr->r_node;
                }
            }
            ptr->r_data = data1;
            ptr->u_data = data2;
            ptr->r_node = NULL;
            ptr->u_node = NULL;
        }

The problem could be that you're trying to access a memory location that doesn't exist. 问题可能是您正在尝试访问不存在的内存位置。 In situations like this, it's always helpful to first check whether the memory location that you want is access is accessible in the first place. 在这种情况下,首先检查您要访问的内存位置是否首先访问总是有帮助的。 In your case, if would help to add something like: 在您的情况下,是否可以帮助添加以下内容:

if(ptr->r_data == data1 && ptr->u_node!=NULL)
   {
    next = ptr->u_node;
    ......

Doing things this way will keep you from falling into segmentation issues. 通过这种方式进行操作可以避免您陷入细分问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM