Browse code

screen: don't leak memory and don't crash if failed to adjust for new screen size

Sigrid Solveig Haflínudóttir authored on 16/07/2023 22:50:19
Showing 2 changed files
... ...
@@ -83,14 +83,20 @@ void
83 83
 screen_resize(Uint16 width, Uint16 height)
84 84
 {
85 85
 	Uint8 *bg, *fg;
86
-	Uint32 *pixels;
86
+	Uint32 *pixels = NULL;
87 87
 	if(width < 0x8 || height < 0x8 || width >= 0x400 || height >= 0x400)
88 88
 		return;
89
-	bg = realloc(uxn_screen.bg, width * height),
90
-	fg = realloc(uxn_screen.fg, width * height);
91
-	pixels = realloc(uxn_screen.pixels, width * height * sizeof(Uint32));
92
-	if(!bg || !fg || !pixels)
89
+	bg = malloc(width * height),
90
+	fg = malloc(width * height);
91
+	if(bg && fg)
92
+		pixels = realloc(uxn_screen.pixels, width * height * sizeof(Uint32));
93
+	if(!bg || !fg || !pixels) {
94
+		free(bg);
95
+		free(fg);
93 96
 		return;
97
+	}
98
+	free(uxn_screen.bg);
99
+	free(uxn_screen.fg);
94 100
 	uxn_screen.bg = bg;
95 101
 	uxn_screen.fg = fg;
96 102
 	uxn_screen.pixels = pixels;
... ...
@@ -293,7 +293,7 @@ capture_screen(void)
293 293
 		return;
294 294
 	SDL_RenderReadPixels(emu_renderer, NULL, format, surface->pixels, surface->pitch);
295 295
 	strftime(fname, sizeof(fname), "screenshot-%Y%m%d-%H%M%S.bmp", localtime(&t));
296
-	if(SDL_SaveBMP(surface, fname) == 0){
296
+	if(SDL_SaveBMP(surface, fname) == 0) {
297 297
 		fprintf(stderr, "Saved %s\n", fname);
298 298
 		fflush(stderr);
299 299
 	}