Skip to main content
GameDev.net gamedev.net
🔒 Locked

Strange Segmentation Fault

Started by KG_Brad May 2, 2008 at 7:04 PM 3 replies 1k views
Original Post
KG_Brad
KG_Brad
The following function, when called, causes a segmentation fault:
BITMAP *grabframe(BITMAP *src,int w,int h,int sx,int sy,int columns,int frame)
{
	BITMAP *temp = create_bitmap(w,h);
		
	int x = sx + frame%columns * w;
	int y = sy + frame/columns * h;
	
	blit(src,temp,x,y,0,0,w,h);
	
	return temp;
}
After much debugging and commenting several lines of code, I narrowed it down to these two lines:
int x = sx + frame%columns * w;
int y = sy + frame/columns * h;
I don't see how this could cause a segmentation fault. What's the problem, here? Also, if it helps, I'm using Dev-C++/gcc. Thank you, -KG_Brad
Quote: Of course justice isn't equal. Rich people can afford lawyers, where poor people get McLawyers.
Palidine
Palidine
when it breaks into the debugger, what's the value of columns?

-me
ukdeveloper
ukdeveloper
BITMAP *grabframe(BITMAP *src,int w,int h,int sx,int sy,int columns,int frame)


You're passing the *src pointer by value. This is therefore a local copy of the pointer which is pointing at nothing (since you're not compensating for this inside the function), and you're then passing this null pointer into another function. The segmentation fault is occurring because your blit() function is probably trying to derefence an unassigned, completely null pointer which could be pointing at any old rubbish in your system memory.

To get around this, you're wanting to either:

a) Pass *src by reference:
BITMAP &src

b) Provide a valid copy constructor/overloaded assignment operator for the BITMAP type, if it's a custom class you wrote (I've never heard of BITMAP as a class type before).

Are you sure this is what you want to do? I would check that, it's a prize-winning recipe for disaster even if it's not the actual problem in this particular case.

(Disclaimer: I'm probably wrong. My C++ is somewhat rusty.)
sphen_lee
sphen_lee
ukdeveloper, there is nothing wrong with passing the BITMAP* by value, that is usually exactly what you want to do (that is not have to make a copy of the bitmap). In C++ it's nicer to use a reference so you don't have to keep dereferencing the pointer, it achieves the same result. However this could be pure C code where a pointer is the only option. The src pointer will only be null if you pass a null pointer when calling this function.

As for the original question, my guess would be a division by 0, check the value of columns.
KG_Brad
KG_Brad
It was dividing by zero. I don't know why I didn't think to check that! It's fixed.

Thanks!
Quote: Of course justice isn't equal. Rich people can afford lawyers, where poor people get McLawyers.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.