简体   繁体   English

分配给返回指针的分段错误

[英]Segmentation error on Assignment to returned pointer

I am curious as to why would assigning a returned pointer to a new pointer variable cause a segmentation fault?我很好奇为什么将返回的指针分配给新的指针变量会导致分段错误? However, passing a pointer into the pop() function as a double pointer would not cause any error.但是,将指针作为双指针传递给 pop() function 不会导致任何错误。

The code below is for testing purposes, I am trying to implement a queue here.下面的代码用于测试目的,我正在尝试在这里实现一个队列。

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;
}

Below is the code that's causing segmentation fault (returnedTask)下面是导致分段错误的代码(returnedTask)

Error: Segmentation fault (core dumped)错误:分段错误(核心转储)

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 definition 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

Node节点

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

I'm going to assume this question has enough content to answer it.我将假设这个问题有足够的内容来回答它。 This is probably a false assumption, and this is probably not the case, which in turn means this is most likely not the actual answer .这可能是一个错误的假设,而且情况可能并非如此,这反过来意味着这很可能不是实际的答案 Nevertheless, I have a point to make.不过,我有一点要说明。 There is a kernel of truth within.里面有一个kernel的真理。

The printfs scattered as they are and almost certainly added one by one to track down the problem eliminate almost all hypotheses. printfs 按原样分散,几乎可以肯定地一一添加以追踪问题,消除了几乎所有假设。

This kind of memory corruption suggests compiling on a 64 bit platform and implicit function declarations were used.这种 memory 损坏表明在 64 位平台上编译并使用隐式 function 声明。 This results in pointer bits being sheared off as it implicitly casts the pointer to int and back.这导致指针位被剪掉,因为它隐式地将指针转换为 int 并返回。 If so, turn on compiler warnings and fix implicit conversion warnings.如果是这样,请打开编译器警告并修复隐式转换警告。

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

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