swapcontext() and Segmentation Fault

I am in the process of trying to analysing a code snippet I just wrote, and am facing a segmentation fault when I try to swap context an a point...

I get a segmentation fault when I call swapcontext() function...

Please guide me.

Can you post the code snippet where you call the "swapcontext" function?

I'm having the same problem-here's my code:

//code snippet from main:
/* context names for scheduler and threads, TODO maybe set up threads as an array? */
ucontext_t sched;
ucontext_t T1;


  /* Set up context and memory for threads, not sure what
   * the flags do
   */
    if(DEBUG){ printf("create context and memory for threads\n");}
    getcontext(&T1);
    if ((T1.uc_stack.ss_sp = malloc(THREAD_STK)) == NULL){
        perror("T1 malloc"), exit(1);      
    }
    T1.uc_stack.ss_flags = 0;
    T1.uc_link = &sched;
    makecontext(&T1, produce_sm, 0);
           
   
    
    /* save main, swap to a thread */
    if(DEBUG){ printf("save sched, swap to T1\n");}
    if(getcontext(&sched) == -1){ /* save main */
        perror("sched get error");
    }

    if ((sched.uc_stack.ss_sp = malloc(THREAD_STK)) == NULL){ /* main stack space */
        die("sched malloc");      
    }
//FAILS HERE
    if(swapcontext(&sched, &T1) == -1){ /* swap to T1 */
        die("sched swap error");
    }

this is the function it's supposed to swap to:

void produce_sm(){
   printf("I'm T1\n"); 
    
   
   printf("swap from T1 to sched\n");
   if(swapcontext(&T1, &sched) == -1){die("T1 swap");}
}

If I ever get this right, its supposed to be a threaded implementation of the
producer-consumer problem. This is my first venture into threads, I'd appreciate any advice.

gebuh, what OS are you using? Most OS'es these days have kernel support for threads. If your kernel does, it will have allocated a thread for you to use. And it looks like you are trying to implement your own user-level threads within that kernel thread. Why take this approach rather than just using pthreads?

I'm on redhat linux, its a class project- we're supposed to implement our own threads, we're limited to make/set/getcontext or set/longjump.

We have some rules here and one of them is:
(6) Do not post classroom or homework problems.

But once in a while we bend the rule a bit, so try setting ss_size when you define the stack.

duly chastened [walk of shame]gonna go read the rules now[/end walk of shame]

Guh.

I'm gonna bend the rules since I feel obliged to point out that longjmp and setcontext are not signal-safe! See 'man signal' for the explicit list of functions that are. So if you're using signals as a trigger to switch contexts you're going to have to throw them out.