I'm trying to implement the simple boundary fill method (using 4 connected approach) for filling a rectangle. I did it as follows (code below), but the rectangle is not getting filled properly: it stops filling when it reaches the half portion of the rectangle.
But the same code works fine when trying to fill a circle. Can anyone help me to figure out the problem?
Thanks in advance
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
void boundfill(int xc, int yc, int r, int b) {
int cur;
cur = getpixel(xc, yc);
if (cur != b && cur != r) {
putpixel(xc, yc, r);
delay(1);
boundfill(xc + 1, yc, r, b);
boundfill(xc - 1, yc, r, b);
boundfill(xc, yc + 1, r, b);
boundfill(xc, yc - 1, r, b);
}
}
void main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "..\\bgi");
rectangle(100, 100, 300, 300);
boundfill(105, 105, 4, WHITE);
getch();
closegraph();
}
Output:
But when I use the following co-ordinates for rectangle, it is working fine. Given co-ordinates:
rectangle(50, 50, 100 ,100);
boundfill(55, 55, 4, WHITE);
For this the output is:
What platform are you using?
BGI is very old Borland gfx API still used for learning purposes if it is original Borland BGI then you are creating 16bit DOS app. There are also wrappers/emulators of BGI for Windows and Linux in that case it depend on your compiler settings.
What can be wrong:
heap/stack
in 16bit DOS mode you can see just first 1 MB of memory space from which is 640KB available for whole system. In your program/project/compiler settings there are additional constraints like initial/maximum heap and stack size for your app. If set too low then you can have heap stack problems in that case it should throw an exception but in my experience I see a lot stranger things then missing exceptions.
When you filling 100x100 pixel area you are recursing up to 10000 times and your recursion call (16bit case) contains:
1 x return address segment+offset = 4 Byte
4 x int16 operand = 8 Byte
1 x int local variable = 2 Byte
all together 14 Byte (on some C/C++ engines truncated to 16 Bytes) not counting additional data need for subcalls like putpixel ... Multiply it by recursion count and you are well above safety for sure on 16 bit DOS. To check this:
to repair this eliminate all unnecessary tings from recursion for example b,r
are constant so they can be in global variable. If you set xc,yc
back to original state before return then you can use &xc,&yc
. Your cur local variable can be static. This will eliminate all allocations in your recursion only the return address remain.
gfx mode
BGI is mostly used for 16 color modes on higher resolutions you are crossing 64KB barriers. If there is something wrong with your BGI driver it could hang up or stop drawing. In that case the stop will occur on the same place no matter the bullet #1. To avoid this change BGI driver, use different resolution or better emulator