简体   繁体   中英

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.

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)

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

#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.

The printfs scattered as they are and almost certainly added one by one to track down the problem eliminate almost all hypotheses.

This kind of memory corruption suggests compiling on a 64 bit platform and implicit function declarations were used. This results in pointer bits being sheared off as it implicitly casts the pointer to int and back. If so, turn on compiler warnings and fix implicit conversion warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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