Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Got this code here that causes a seg fault. How do I prevent the seg fault from happening ( not the full code but just the part that is apparently causing it.)
unsigned char* pixel_offset = data + (j + width * i) * byte_per_pixel;
unsigned char y = pixel_offset[0];


What I have tried:

Searching on the internet and asking around on other different forums has turned up nothing so far.
Posted
Updated 23-Jan-23 18:07pm

1 solution

Segment faults are caused by attempting to address an invalid address. I will assume data is a pointer to the base of an image buffer. What you can do is check the validity of the rest of that expression. That means you can write a function that looks something like this :
C
int IsValidPixelOffset( int i, int j, int width, int bufferSize )
{
   int offset = ( j + width * i ) * byte_per_pixel;
   if( offset < bufferSize )
       return 1;       // valid offset

   return 0;           // invalid offset
}
Call this function before dereferencing the pointer and it should tell you if will you have a valid address or not. The function signature and implementation will likely have to change to suit your application. If it tells you the offset is correct and you still get a fault then your buffer was probably not allocated to be large enough.
 
Share this answer
 
Comments
CPallini 24-Jan-23 2:24am    
5.
Chillzy 24-Jan-23 10:26am    
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900