Reputation: 4336
My code when run within Valgrind gives a segmentation fault, but when run normally it doesn't. How is this possible?
The culprit piece of code ,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 the message by valgrind:
Process terminating with default action of signal 11 (SIGSEGV)
==3290== Access not within mapped region at address 0x0
Why does this happen, if normally the code runs perfectly? How do I fix this? I need to do some memory profiling of the code.
Upvotes: 4
Views: 7187
Reputation: 3005
As mentioned in comments, undefined behavior does not have to involve a crash. It could function perfectly well. However, that does not appear to be the case here.
We can see from the message
Process terminating with default action of signal 11 (SIGSEGV)
==3290== Access not within mapped region at address 0x0
That the program has attempted to access address 0x0. This typically 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 can see that you have attempted to guard against invalid parameters, by asserting that i>=0
and i<p->nSize
. There is however, no check that p
itself is valid.
You could assert(p)
to ensure it is not NULL. You should do this before the existing assertion.
As to why this only occurs when running under valgrind, an important consideration is that programs run MUCH slower under valgrind, and so you may have exposed an issue that only occurs under heavy load, or at least very different dynamic behavior to the norm.
How can you resolve this and move forward with memory profiling? You need to fix the bug.
Either of these should allow you to see the back-trace, and figure out why p is NULL.
Upvotes: 3