简体   繁体   中英

Keep segfaulting when trying to pass struct into function

I'm trying to pass a pointer to a queue into the createQueue function:

void createQueue(struct pqueue *queue){
    queue = malloc( sizeof(struct pqueue) );  
    queue->root = malloc(sizeof(struct node));
    queue->root->next = 0;   
    queue->root->taskID = 12;
    queue->root->priority = 5000;
}

I also try to add to the newly created queue like this:

void add(struct pqueue *queue, int taskID, int priority){
struct node *conductor;
conductor = queue->root;
if ( conductor != 0 ) {
        while ( conductor->next != 0)
        {
                conductor = conductor->next;
        }
}
 conductor->next = malloc( sizeof(struct node) );  
 conductor = conductor->next;
 if ( conductor == 0 )
  {
      printf( "Out of memory" );
  }
  /* initialize the new memory */
  conductor->next = 0;         
  conductor->taskID = taskID;
  conductor->priority = priority;
}

from the main function:

int main()
{
    struct pqueue *queue;       

    createQueue(queue);
    add(queue, 234093, 9332);
}

...but I keep segfaulting. Any reason why this keeps happening?

EDIT:

The structs for pqueue and node are like this:

struct node {
  int taskID;
  int priority;
  struct node *next;
};

struct pqueue{
  struct node *root;
};

In C, everything is passed by value. Therefore, when you call createQueue(queue) , you are passing a copy of the pointer to the function. Then, inside the function, when you say queue = malloc(...) , you are setting that copy of the pointer equal to your newly allocated memory - leaving main() 's copy of that pointer unchanged.

You want to do something like this:

void createQueue(struct pqueue **queue)
{
    (*queue) = malloc( ... );
}

int main(void)
{
    struct pqueue *queue;

    createQueue(&queue);
}

This question has a more detailed description of what's going wrong for you.

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