Avoid memory leak on failed realloc(3)

This commit is contained in:
Xavier Del Campo Romero 2023-04-30 17:07:00 +02:00
parent c3fbb34a69
commit 83aabf0185
5 changed files with 34 additions and 10 deletions

View File

@ -16,7 +16,7 @@ enum
};
int sprite_screen_resize_ev(struct sprite *s);
void gfx_register_sprite(struct sprite *s);
int gfx_register_sprite(struct sprite *s);
SDL_Surface *gfx_screen(void);
#ifdef __cplusplus

View File

@ -2,10 +2,12 @@
#include <gfx_private.h>
#include <sdl-1.2/gfx_private.h>
#include <SDL.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int screen_w = SCREEN_W, screen_h = SCREEN_H;
static bool fullscreen;
@ -25,12 +27,19 @@ static struct
int w, h;
} display, windowed;
void gfx_register_sprite(struct sprite *const s)
int gfx_register_sprite(struct sprite *const s)
{
list = realloc(list, (list_len + 1) * sizeof *list);
struct sprite **const l = realloc(list, (list_len + 1) * sizeof *list);
if (list)
list[list_len++] = s;
if (!l)
{
fprintf(stderr, "%s: realloc(3): %s\n", __func__, strerror(errno));
return -1;
}
list = l;
list[list_len++] = s;
return 0;
}
static int resize_screen(int w, int h, const bool full_screen)

View File

@ -99,8 +99,12 @@ static int load_bitmap(struct sprite *const s, FILE *const f)
fprintf(stderr, "SDL_DisplayFormat: %s\n", SDL_GetError());
goto end;
}
else if (gfx_register_sprite(s))
{
fprintf(stderr, "gfx_register_sprite failed\n");
goto end;
}
gfx_register_sprite(s);
s->w = ts->w;
s->h = ts->h;
ret = 0;

View File

@ -104,12 +104,16 @@ static int free_req(struct net_host_domain *const h, struct req *const r)
if (n)
{
if (!(h->reqs = realloc(h->reqs, n * sizeof *h->reqs)))
struct req *const r = realloc(h->reqs, n * sizeof *h->reqs);
if (!r)
{
fprintf(stderr, "%s: realloc(3) failed: %s\n",
__func__, strerror(errno));
return -1;
}
h->reqs = r;
}
else
{
@ -127,13 +131,18 @@ static int free_req(struct net_host_domain *const h, struct req *const r)
static struct req *alloc_req(struct net_host_domain *const h,
const void *const buf, const size_t n, const enum req_type t)
{
if (!(h->reqs = realloc(h->reqs, (h->n_reqs + 1) * sizeof *h->reqs)))
struct req *const reqs = realloc(h->reqs,
(h->n_reqs + 1) * sizeof *h->reqs);
if (!reqs)
{
fprintf(stderr, "%s: realloc(3) failed: %s\n",
__func__, strerror(errno));
return NULL;
}
h->reqs = reqs;
struct req *const r = &h->reqs[h->n_reqs++];
*r = (const struct req)

View File

@ -55,11 +55,13 @@ union transport_packet *transport_packet_alloc(const enum transport_packet_type
int transport_append(struct transport_handle *const h,
union transport_packet *const p)
{
h->packets = realloc(h->packets, (h->n_packets + 1) * sizeof *h->packets);
union transport_packet **const packets = realloc(h->packets,
(h->n_packets + 1) * sizeof *h->packets);
if (!h->packets)
if (!packets)
return -1;
h->packets = packets;
h->packets[h->n_packets++] = p;
return 0;
}