Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c - 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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...