1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-07-02 16:38:41 +00:00

Less explicit memory management in Irrlicht image writer classes (#15493)

CImageWriterPNG::writeImage() and writeJPEGFile() explicitly allocate
and deallocate memory with `new` and `delete`, which is prone to programming errors.
The code also has non-functional error handling:
When memory allocation fails, `new` throws an `std::bad_alloc` exception
and never returns `nullptr`, so the check for `nullptr` is always false.

Co-authored-by: DS <ds.desour@proton.me>
This commit is contained in:
HybridDog 2024-12-03 16:52:48 +01:00 committed by GitHub
parent 03813a5b5e
commit a45b04ffb4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 34 additions and 46 deletions

View file

@ -10,6 +10,7 @@
#include "os.h"
#include <cstdio> // IWYU pragma: keep (required for jpeglib.h)
#include <memory>
#include <jpeglib.h>
#include <jerror.h>
@ -130,32 +131,28 @@ static bool writeJPEGFile(io::IWriteFile *file, IImage *image, u32 quality)
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress(&cinfo, TRUE);
u8 *dest = new u8[dim.Width * 3];
std::unique_ptr<u8[]> dest{new u8[dim.Width * 3]};
if (dest) {
const u32 pitch = image->getPitch();
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
row_pointer[0] = dest;
const u32 pitch = image->getPitch();
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
row_pointer[0] = dest.get();
u8 *src = (u8 *)image->getData();
u8 *src = (u8 *)image->getData();
while (cinfo.next_scanline < cinfo.image_height) {
// convert next line
format(src, dim.Width, dest);
src += pitch;
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
delete[] dest;
/* Step 6: Finish compression */
jpeg_finish_compress(&cinfo);
while (cinfo.next_scanline < cinfo.image_height) {
// convert next line
format(src, dim.Width, dest.get());
src += pitch;
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
/* Step 6: Finish compression */
jpeg_finish_compress(&cinfo);
/* Step 7: Destroy */
jpeg_destroy_compress(&cinfo);
return (dest != 0);
return true;
}
} // namespace video