Segmentation fault in valgrind but not realtime

My code, when running inside Valgrind, gives a segmentation fault, but it usually does not when run. How is this possible?

The code caster as pointed out by valgrind:

static inline void * Vec_PtrEntry( Vec_Ptr_t * p, int i )
{
    assert( i >= 0 && i < p->nSize );
    return p->pArray[i];
}

      

And valgrind's post:

Process terminating with default action of signal 11 (SIGSEGV)
==3290==  Access not within mapped region at address 0x0

      

Why does this happen if the code usually works fine? How to fix it? I need to do some code profiling.

+3


source to share


1 answer


As mentioned in the comments, undefined behavior doesn't have to crash. It can function perfectly. However, this does not seem to be the case.

From post

it is seen,
Process terminating with default action of signal 11 (SIGSEGV)
==3290==  Access not within mapped region at address 0x0

      

For the program to try to access address 0x0. This usually means that we have dereferenced a NULL pointer.

Looking at your code:

static inline void * Vec_PtrEntry( Vec_Ptr_t * p, int i )
{
    assert( i >= 0 && i < p->nSize );
    return p->pArray[i];
}

      



We see that you were trying to protect against invalid parameters by arguing that i>=0

and i<p->nSize

. However, there is no verification of that myself p

.

You can assert(p)

make sure it is not NULL. You must do this prior to the existing approval.

As for why this only happens when run under valgrind, it is important to consider that programs run MUCH slower under valgrind, so you may run into a problem that only occurs under heavy load, or at least very different dynamic behavior normally.

How can you solve this problem and move forward with memory profiling? You need to fix the error.

  • Use a debugger. gdb pairs nicely with valgrind
  • Use assertions to check that p is not null.

Either one should allow you to see a backtrace and figure out why p is NULL.

+3


source







All Articles