1

When I run my program, I get segmentation fault, so I decided to check it through Valgrind. When I did, I got the following message from Valgrind. And I get the error when I use the code described here. Any idea what is going on here?

==21471== Invalid write of size 8
==21471==    at 0x4802511: _vgnU_freeres (vg_preloaded.c:64)
==21471==    by 0x38A715397F: ???
==21471==    by 0x38A6E4D549: printf (in /lib64/libc-2.5.so)
==21471==    by 0x401D52: call_func(int) (replication.cpp:752)
==21471==    by 0x6137C7: ???
==21471==    by 0x40621C: AdvanceFramesMT(void*) (pthreads.cpp:1020)
==21471==    by 0x38A7A0673C: start_thread (in /lib64/libpthread-2.5.so)
==21471==    by 0x38A6ED44BC: clone (in /lib64/libc-2.5.so)
==21471==  Address 0x612ba8 is 14216 bytes inside data symbol "func_stack"

Code

static char func_stack[16384];
static ucontext_t uctx_main[16], uctx_func[16];

void call_func( int n )
{
    printf( "Message %d!", n );
}

 if (getcontext(&uctx_func[tid]) == -1)
        handle_error("getcontext");
 uctx_func[tid].uc_stack.ss_sp = func_stack;
 uctx_func[tid].uc_stack.ss_size = sizeof(func_stack);
 uctx_func[tid].uc_link = &uctx_main[tid];
 makecontext(&uctx_func[tid], (void(*)())call_func, 1, 2);

 if (swapcontext(&uctx_main[tid], &uctx_func[tid]) == -1)
    handle_error("swapcontext");  
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • 1
    If I just copy the code you show it works fine for me, both when running and in valgrind. The error must be because of something else. – Some programmer dude Nov 16 '11 at 07:23
  • 1
    Did you check that `tid` always lies between and `0` and `15`? – Frédéric Hamidi Nov 16 '11 at 07:25
  • You haven't identified line 752 in `replication.cpp` (or line 1020 in `pthreads.cpp`, though that may not matter). It isn't clear whether it is complaining about an 8-bytes-at-a-time write into a character array; it is a bit unlikely, though. It might be misalighed, though...or, if not misaligned, then sub-optimally aligned. – Jonathan Leffler Nov 16 '11 at 07:29
  • 3
    @MetallicPriest: please show the actual code preferably with file names and line numbers and not some random pieces of code that even don't look as one piece. – wRAR Nov 16 '11 at 07:38

2 Answers2

3

Try to improve Valgrind stack traces - this will hopefully help to understand the problem. Are you using -fomit-frame-pointer or -fstack-check gcc options? This can make Valgrind stack traces worse (with ??? symbols instead of names) Valgrind FAQ.

ks1322
  • 33,961
  • 14
  • 109
  • 164
3

OK, I got it now. Actually I was using this for multiple threads. That is why uctx_main[16] and uctx_func[16] are arrays. However, I forgot to make func_stack also an array (a 2-dimensional array in fact). So I changed it to char func_stack[16][16384] and it solved the problem.

Stedy
  • 7,359
  • 14
  • 57
  • 77
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356