4

我目前面临一个非常奇怪的问题。我正在构建一个库并将其链接到我的程序。一切运行良好,没有分段错误(也使用 gdb 检查)但是当我使用 Valgrind 运行程序时,它会因为以下行而疯狂:

==11972== Invalid read of size 8
==11972==    at 0x509509C: setcontext (setcontext.S:73)
==11972==    by 0x509764F: ??? (in /lib/x86_64-linux-gnu/libc-2.15.so)
==11972==  Address 0x541f060 is 128 bytes inside a block of size 936 alloc'd
==11972==    at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11972==    by 0x402090: environment_get (env.c:99)
==11972==    by 0x401ED6: environment_new (env.c:36)
==11972==    by 0x40124B: thr_new (thr.c:156)
==11972==    by 0x400EBE: main (itest1.c:31)

但是程序运行良好,并且setcontext有一个正确分配的参数,没有问题。我有什么理由担心这些台词吗?

谢谢

4

1 回答 1

2

晚了七年才开始讨论这个问题,但是:我通过确保我的堆栈至少是SIGSTKSZ. 所以,下面的代码可以解决这个问题:

#include <valgrind/valgrind.h>

//technically, the below doesn't need to be dynamically allocated, but for demonstration:
ucontext_t context = (ucontext_t*) malloc(sizeof(ucontext_t));

getcontext(&context);
void* stack = malloc(SIGSTKSZ);
VALGRIND_STACK_REGISTER(stack, stack + SIGSTKSZ);
context->uc_stack.ss_sp     = stack;
context->uc_stack.ss_size   = SIGSTKSZ;
context->uc_stack.ss_flags  = 0;
sigemptyset(&context->uc_sigmask);
context->uc_link            = &someOtherContextToGoToAfterwards;
makecontext(context, functionForContextToExecute);

然后,在清理它时,您可以做一些负责任的事情,例如:

VALGRIND_STACK_DEREGISTER(context->uc_stack.ss_sp);
free(context->uc_stack.ss_sp);
free(context).
于 2020-04-15T22:33:41.970 回答