Repair memory leaks in plpython.
[pgsql.git] / src / common / fe_memutils.c
blob4ba793a6132bb26353887471c009c3eccb9a0e87
1 /*-------------------------------------------------------------------------
3 * fe_memutils.c
4 * memory management support for frontend code
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * src/common/fe_memutils.c
13 *-------------------------------------------------------------------------
16 #ifndef FRONTEND
17 #error "This file is not expected to be compiled for backend code"
18 #endif
20 #include "postgres_fe.h"
22 static inline void *
23 pg_malloc_internal(size_t size, int flags)
25 void *tmp;
27 /* Avoid unportable behavior of malloc(0) */
28 if (size == 0)
29 size = 1;
30 tmp = malloc(size);
31 if (tmp == NULL)
33 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
35 fprintf(stderr, _("out of memory\n"));
36 exit(EXIT_FAILURE);
38 return NULL;
41 if ((flags & MCXT_ALLOC_ZERO) != 0)
42 MemSet(tmp, 0, size);
43 return tmp;
46 void *
47 pg_malloc(size_t size)
49 return pg_malloc_internal(size, 0);
52 void *
53 pg_malloc0(size_t size)
55 return pg_malloc_internal(size, MCXT_ALLOC_ZERO);
58 void *
59 pg_malloc_extended(size_t size, int flags)
61 return pg_malloc_internal(size, flags);
64 void *
65 pg_realloc(void *ptr, size_t size)
67 void *tmp;
69 /* Avoid unportable behavior of realloc(NULL, 0) */
70 if (ptr == NULL && size == 0)
71 size = 1;
72 tmp = realloc(ptr, size);
73 if (!tmp)
75 fprintf(stderr, _("out of memory\n"));
76 exit(EXIT_FAILURE);
78 return tmp;
82 * "Safe" wrapper around strdup().
84 char *
85 pg_strdup(const char *in)
87 char *tmp;
89 if (!in)
91 fprintf(stderr,
92 _("cannot duplicate null pointer (internal error)\n"));
93 exit(EXIT_FAILURE);
95 tmp = strdup(in);
96 if (!tmp)
98 fprintf(stderr, _("out of memory\n"));
99 exit(EXIT_FAILURE);
101 return tmp;
104 void
105 pg_free(void *ptr)
107 free(ptr);
111 * Frontend emulation of backend memory management functions. Useful for
112 * programs that compile backend files.
114 void *
115 palloc(Size size)
117 return pg_malloc_internal(size, 0);
120 void *
121 palloc0(Size size)
123 return pg_malloc_internal(size, MCXT_ALLOC_ZERO);
126 void *
127 palloc_extended(Size size, int flags)
129 return pg_malloc_internal(size, flags);
132 void
133 pfree(void *pointer)
135 pg_free(pointer);
138 char *
139 pstrdup(const char *in)
141 return pg_strdup(in);
144 char *
145 pnstrdup(const char *in, Size size)
147 char *tmp;
148 int len;
150 if (!in)
152 fprintf(stderr,
153 _("cannot duplicate null pointer (internal error)\n"));
154 exit(EXIT_FAILURE);
157 len = strnlen(in, size);
158 tmp = malloc(len + 1);
159 if (tmp == NULL)
161 fprintf(stderr, _("out of memory\n"));
162 exit(EXIT_FAILURE);
165 memcpy(tmp, in, len);
166 tmp[len] = '\0';
168 return tmp;
171 void *
172 repalloc(void *pointer, Size size)
174 return pg_realloc(pointer, size);