【问题标题】:Exception thrown: read access violation. it was 0xFDFDFDFD抛出异常:读取访问冲突。它是 0xFDFDFDFD
【发布时间】:2021-05-01 20:28:15
【问题描述】:

我是 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");

}

【问题讨论】:

  • 提供一个演示问题的最小完整程序。

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


【解决方案1】:

问题的原因似乎是此声明中指定的分配内存大小不正确

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。

【讨论】:

  • 我根据您提出的解决方案和建议更新了代码。我很感激你的帮助。谢谢!
  • @lalaliha 要关闭问题,请选择最佳答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2020-09-12
  • 1970-01-01
  • 2018-05-19
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多