c - swapcontext() 段错误

标签 c segmentation-fault

我正在尝试使用 swapcontext() 创建一个简单的 hello world 示例

这是代码片段:

#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);
}

但问题是当程序执行 swapcontext() 时发生段错误。我摆弄了一下,发现问题是我分配给上下文的堆栈大小,但我不知道我做错了什么。

附言我已经尝试分配 sizeof(func1_stack) 但仍然出现段错误

谁能给我一个提示?

最佳答案

使用 64 作为编码的堆栈大小与实际给定的堆栈大小一致。然而,64 字节对于堆栈来说是相当小的。 example here使用 16K 作为堆栈大小。可能是您使用的尺寸太小了。

顺便说一句,memset 可能不正确。它设置数组的前 10 个字节。它实际上并没有影响任何东西,但它可能应该是以下内容:

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

关于c - swapcontext() 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763970/

相关文章:

c++ - 在linux中用gcc命令编译C代码时如何包含lib

c - 扫描输入字符串并将单词存储在 C 数组中

c - strcpy 没有空间容纳空终止符,那么它打印什么呢?

c - 如何在命令行应用程序中使用 Instruments 和显示控制台

c++ - 成功打印超出范围的字符串索引

c - 当我创建并向结构添加值时发生了一些事情,导致了段错误

c - 如何修复此代码以创建字符串数组?

c++ - 非常奇怪的段错误调用 WinUsb_GetOverlappedResult

c - 程序收到信号SIGSEGV、段错误、链表程序

C:字符到位并打印