抛出异常:读取访问冲突。它是 0xFDFDFDFD

时间:2021-01-27 23:04:57

标签: c linked-list dynamic-memory-allocation singly-linked-list function-definition

我是 C 和数据结构的初学者,遇到了令人沮丧的异常。我和其他双向链表代码对比过,没找到错误。

在调试代码时,我从 stdio.h 收到关于读取访问冲突的警告,这是有问题的部分:

<块引用>

return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList);

你能帮我吗?

struct Node* NewNode() {

    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
    new_node->next = NULL;
    new_node->prev = NULL;
    return new_node;

}

void InsertElement(char con, char name[51]) {

    struct Node* new_node = NewNode();
    strcpy(new_node->name,name);
    
    if (head == NULL) {
        head = new_node;
        tail = head;
        return;
    }
    
    if (con == 'H') {
        head->prev = new_node;
        new_node->next = head;
        head = new_node;
    }
    
    else if (con == 'T') {
        tail->next = new_node;
        new_node->prev = tail;
        tail = new_node;
    }

}

void DisplayForward() {

    if (head == NULL) {
        printf("No Songs To Print\n*****\n");
        return;
    }
    struct Node *temp = head;
    while (temp != NULL) {
        printf("%s\n", temp->name);
        temp = temp->next;
    }
    printf("*****\n");
}

void DisplayReversed() {

    if (head == NULL) {
        printf("No Songs To Print\n*****\n");
        return;
     }
    
    struct Node *temp = tail;
    while (temp != NULL) {
        printf("%s\n", temp->name);
        temp = temp->prev;
    }
    printf("*****\n");

}

1 个答案:

答案 0 :(得分:0)

看来问题的原因是这个声明中指定的分配内存大小不正确

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
                                                    ^^^^^^^^^^^^

你必须写

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
                                                    ^^^^^^^^^^^^

也就是说,您需要为 struct Node 类型的对象分配内存,而不是为 struct Node * 类型的指针分配内存。

注意函数InsertElement是不安全的,因为用户可以为参数con指定错误的值。在这种情况下,函数会产生内存泄漏,因为分配的节点不会被插入到链表中,退出函数后为节点分配的内存地址将丢失。

最好编写两个函数,其中一个将节点附加到列表的开头,另一个 - 附加到列表的末尾。在这种情况下,将不需要参数 con。

相关问题