I'm working with a Uint8 array of pixels in SFML, and trying to update them all to appear white/0xFF/255 as a test, but for some reason using a for loop does nothing and I have no idea why, the logic should make perfect sense.
Using a memset() to set every byte to 0xFF works perfectly, but occasionally throws EXC_BAD_ACCESS at me upon running. Setting each of the RGBA of an individual pixel in the array to 0xFF works perfectly, I get a white dot on my screen at the correct location. But using a for loop to set every pixel to 0xFF does nothing, no error, but no result, which makes no sense.
// Create buffer
sf::Uint8 *buffer = new sf::Uint8[SCREEN_WIDTH*SCREEN_HEIGHT*4];
for(int i; i < SCREEN_WIDTH*SCREEN_HEIGHT*4; i+=4) {
buffer[i] = 0xFF;
buffer[i+1] = 0xFF;
buffer[i+2] = 0xFF;
buffer[i+3] = 0xFF;
}
Logically this for loop should work perfectly, but it does not, when I run this I have a black screen with some green dots spread around the middle (garbage from the memory locations being used). If anyone can explain to me why this is happening and how to fix it I would greatly appreciate it!
for(int i; i < SCREEN_WIDTH*SCREEN_HEIGHT*4; i+=4) {
You never set an initial value for i
here, so it will have some indeterminate value, and in practice probably one larger enough for it to never loop at all. c and c++ do not initialise local primitive types by default, you must set a value.
for(int i = 0; i < SCREEN_WIDTH*SCREEN_HEIGHT*4; i+=4) {
As for EXC_BAD_ACCESS
, you must have passed the wrong memory address or size to memset
. Maybe another uninitialised variable?
In C/C++ accessing memory outside of an object often has no facility to catch the error (unlike many other languages that will range check every array access to give say a IndexOutOfRangeException
), and it will just overwrite some random bytes, and maybe if you are lucky that is a completely invalid memory location and the OS/processor raises an error.