We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 4931

Summary: Improper indexing of locked texture buffers
Product: SDL Reporter: sdl2
Component: renderAssignee: Sam Lantinga <slouken>
Status: RESOLVED INVALID QA Contact: Sam Lantinga <slouken>
Severity: minor    
Priority: P2    
Version: 2.0.10   
Hardware: x86_64   
OS: Linux   
Attachments: Image of bug

Description sdl2 2020-01-07 22:35:03 UTC
Created attachment 4154 [details]
Image of bug

I would expect the following C code to fill in a window with red pixels, instead it seems like it skips a byte at the end of each row (see image) thus creating an ugly pattern.

void main(){
	int width = 14;
	int height = 16;

	int pitch = width*3;
	uint8_t *pixels;

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
		fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
		return EXIT_FAILURE;
	}

	SDL_Window * window = SDL_CreateWindow(
		"Illustration",
		SDL_WINDOWPOS_UNDEFINED, 
		SDL_WINDOWPOS_UNDEFINED, 
		width*10, 
		height*10, 
		SDL_WINDOW_RESIZABLE
	);

	SDL_Renderer * renderer;
	renderer = SDL_CreateRenderer(
		window,
		-1,
		SDL_RENDERER_ACCELERATED
	);

	SDL_Texture * buffer = SDL_CreateTexture(
		renderer,
		SDL_PIXELFORMAT_RGB24, // char red, char blue, char green
		SDL_TEXTUREACCESS_STREAMING, 
		width, height
	);

	for (int i = 0; i < width*height; ++i)	
	{
		SDL_LockTexture (buffer, NULL, (void **) &pixels, &pitch);

		int index = i*3;
		pixels[index]   = 255; // red
		pixels[index+1] = 0;   // green
		pixels[index+2] = 0;   // blue

		SDL_UnlockTexture(buffer);	
		SDL_RenderCopy(renderer, buffer, NULL, NULL);
		SDL_RenderPresent(renderer);
		SDL_Delay(10);
	}
	
	// I will spare you all the free()
}
Comment 1 sdl2 2020-01-07 23:13:16 UTC
I was told on the forums that the correct way to do this is

 int index = (i / width) * pitch + (i % width) * 3 ;

This solved the problem so I guess it's not a bug. Still seems like odd behaviour though.
Comment 2 sdl2 2020-01-07 23:15:12 UTC
changed status