【问题标题】:Segmentation error on Assignment to returned pointer分配给返回指针的分段错误
【发布时间】:2021-02-10 04:30:13
【问题描述】:

我很好奇为什么将返回的指针分配给新的指针变量会导致分段错误?但是,将指针作为双指针传递给 pop() 函数不会导致任何错误。

下面的代码是测试用的,我这里尝试实现一个队列。

void push(struct node **head, Task * newTask) {
    struct node* temp = malloc(sizeof(struct node));
    temp->task = newTask;
    temp->next = NULL;
    struct node* curr = *head;
    if (*head == NULL) {
        puts("Entered here");
        temp->next = *head;
        *head = temp;
    } else {
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = temp;
    }
}

Task* pop(struct node** head, Task** returnTask) {
    struct node* returnNode = *head;
    *returnTask = returnNode->task;
    *head = returnNode->next;
    free(returnNode);
    printf("%s\n", (*returnTask)->name);
    return *returnTask;
}

下面是导致分段错误的代码(returnedTask)

错误:分段错误(核心转储)

void schedule() {
    struct node* queue = NULL;
    Task* currTask = pickNextTask(); //Returns a Task
    push(&queue, currTask);
    Task* newTask = NULL;
    Task* returnedTask = pop(&queue, &newTask);
    printf("%s", newTask->name); //Runs fine
    printf("%s", returnedTask->name);  //Segmentation fault
}

Task.h 定义

#ifndef TASK_H
#define TASK_H

// representation of a task
typedef struct task {
    char *name;
    int tid;
    int priority;
    int burst;
} Task;

#endif

节点

struct node {
    Task *task;
    struct node *next;
};

【问题讨论】:

  • 请提供完整的示例,以便我们查看结构定义等...另外,请提供确切的错误消息
  • @the_endian 它已更新!谢谢你告诉我
  • 我看不出您的示例(不是minimal reproducible example BTW)为什么会出错。这个对我有用。请提供minimal reproducible example
  • 当您访问name 时我们无法首先看到name 是如何获取其值的,我们如何解决错误?你需要给我们足够的代码来重现问题。

标签: c


【解决方案1】:

我假设这个问题有足够的内容来回答它。这可能是一个错误的假设,而且可能并非如此,这反过来意味着这很可能不是实际答案。不过,我有一点要说明。里面有一个真理的内核。

printfs 按原样分散,几乎可以肯定是一一添加来追踪问题,几乎消除了所有假设。

这种内存损坏表明在 64 位平台上编译并使用了隐式函数声明。这导致指针位被剪掉,因为它隐式地将指针转换为 int 并返回。如果是这样,请打开编译器警告并修复隐式转换警告。

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多