user1162954
user1162954

Reputation: 267

swapcontext() segmentation fault

I am trying to create a simple hello world example using swapcontext()

Here is the code snippet:

#include <ucontext.h>
#include <stdio.h>
#include <stdlib.h>

static ucontext_t uctx_main, uctx_func1;

typedef struct test_struct 
{
    ucontext_t  context;
    int value;
}test_struct;

test_struct* array[10];

static void
func1(void)
{
    printf("func1: started\n");
    printf("func1: TESTING\n");
    printf("func1: returning\n");
}
void init()
{
    memset(array,NULL,10);

    array[0] = (test_struct*)malloc(sizeof(test_struct));
    array[0]->value = 10;

    getcontext(&array[0]->context);

    char* func1_stack = (char*)malloc(sizeof(char)*64);
    //char func1_stack[64];

    array[0]->context.uc_stack.ss_sp = func1_stack;
    array[0]->context.uc_stack.ss_size = 64;
    array[0]->context.uc_link = &uctx_main;

    makecontext(&array[0]->context, func1, 0);
}

int main(int argc, char *argv[])
{
   init();

   printf("VALUE: %d\n",array[0]->value);

   swapcontext(&uctx_main, &array[0]->context);

   printf("VALUE: %d\n",array[0]->value);
   printf("main: exiting\n");
   exit(0);
}

But the problem is when the progam executes swapcontext() a segmentation fault occurs. I have fiddled around a bit and I figured out that the problem is the stack size that I am assigning to the context but I don't know what I am doing wrong.

P.S. I have tried assigning sizeof(func1_stack) but still got a seg fault

Can anyone give me a hint?

Upvotes: 1

Views: 2762

Answers (1)

Mark Wilkins
Mark Wilkins

Reputation: 41252

Using 64 as the stack size as coded is consistent with the actual given stack size. However, 64 bytes is fairly small for a stack. The example here uses 16K as the stack size. It may be that the size you are using is simply too small.

As an aside, the memset is probably not correct. It is setting the first 10 bytes of the array. It is not actually affecting anything, but it should probably be the following:

memset(array,0,sizeof(array)));

Upvotes: 2

Related Questions