}
                                break;
                        case 't':                       /* Trigger file */
-                               triggerPath = strdup(optarg);
+                               triggerPath = pg_strdup(optarg);
                                break;
                        case 'w':                       /* Max wait time */
                                maxwaittime = atoi(optarg);
 
 
                if (!schema || !table || !field)
                {
-                       fprintf(stderr, "Out of memory\n");
+                       fprintf(stderr, "%s", PQerrorMessage(conn));
                        PQclear(res);
                        PQfinish(conn);
                        if (schema != NULL)
                                }
                                break;
                        case 'U':
-                               param.pg_user = strdup(optarg);
+                               param.pg_user = pg_strdup(optarg);
                                break;
                        case 'w':
                                param.pg_prompt = TRI_NO;
                                        fprintf(stderr, "%s: invalid port number: %s\n", progname, optarg);
                                        exit(1);
                                }
-                               param.pg_port = strdup(optarg);
+                               param.pg_port = pg_strdup(optarg);
                                break;
                        case 'h':
-                               param.pg_host = strdup(optarg);
+                               param.pg_host = pg_strdup(optarg);
                                break;
                }
        }
 
 uint32         bootstrap_data_checksum_version = 0;            /* No checksum */
 
 
-#define ALLOC(t, c)            ((t *) calloc((unsigned)(c), sizeof(t)))
+#define ALLOC(t, c) \
+       ((t *) MemoryContextAllocZero(TopMemoryContext, (unsigned)(c) * sizeof(t)))
 
 static void CheckerModeMain(void);
 static void BootstrapModeMain(void);
                                SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
                                break;
                        case 'D':
-                               userDoption = strdup(optarg);
+                               userDoption = pstrdup(optarg);
                                break;
                        case 'd':
                                {
 static Form_pg_attribute
 AllocateAttribute(void)
 {
-       Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_FIXED_PART_SIZE);
-
-       if (!PointerIsValid(attribute))
-               elog(FATAL, "out of memory");
-       MemSet(attribute, 0, ATTRIBUTE_FIXED_PART_SIZE);
-
-       return attribute;
+       return (Form_pg_attribute)
+               MemoryContextAllocZero(TopMemoryContext, ATTRIBUTE_FIXED_PART_SIZE);
 }
 
 /*
 
        NSSymbol symbol;
        char       *symname = (char *) malloc(strlen(funcname) + 2);
 
+       if (!symname)
+               return NULL;
+
        sprintf(symname, "_%s", funcname);
        if (NSIsSymbolNameDefined(symname))
        {
 
  * overwritten during init_ps_display.  Also, the physical location of the
  * environment strings may be moved, so this should be called before any code
  * that might try to hang onto a getenv() result.)
+ *
+ * Note that in case of failure this cannot call elog() as that is not
+ * initialized yet.  We rely on write_stderr() instead.
  */
 char     **
 save_ps_display_args(int argc, char **argv)
                 * move the environment out of the way
                 */
                new_environ = (char **) malloc((i + 1) * sizeof(char *));
+               if (!new_environ)
+               {
+                       write_stderr("out of memory\n");
+                       exit(1);
+               }
                for (i = 0; environ[i] != NULL; i++)
+               {
                        new_environ[i] = strdup(environ[i]);
+                       if (!new_environ[i])
+                       {
+                               write_stderr("out of memory\n");
+                               exit(1);
+                       }
+               }
                new_environ[i] = NULL;
                environ = new_environ;
        }
                int                     i;
 
                new_argv = (char **) malloc((argc + 1) * sizeof(char *));
+               if (!new_argv)
+               {
+                       write_stderr("out of memory\n");
+                       exit(1);
+               }
                for (i = 0; i < argc; i++)
+               {
                        new_argv[i] = strdup(argv[i]);
+                       if (!new_argv[i])
+                       {
+                               write_stderr("out of memory\n");
+                               exit(1);
+                       }
+               }
                new_argv[argc] = NULL;
 
 #if defined(__darwin__)
 
                                dryrun = true;
                                break;
                        case 'x':
-                               additional_ext = strdup(optarg);                /* Extension to remove
+                               additional_ext = pg_strdup(optarg);             /* Extension to remove
                                                                                                                 * from xlogfile names */
                                break;
                        default:
 
                                        fflush(stdout);
                                }
                                result = gets_fromFile(stdin);
+                               if (!result)
+                               {
+                                       psql_error("\\%s: could not read value for variable\n",
+                                                          cmd);
+                                       success = false;
+                               }
                        }
 
-                       if (!SetVariable(pset.vars, opt, result))
+                       if (result &&
+                               !SetVariable(pset.vars, opt, result))
                        {
                                psql_error("\\%s: error while setting variable\n", cmd);
                                success = false;
                        }
 
-                       free(result);
+                       if (result)
+                               free(result);
                        if (prompt_text)
                                free(prompt_text);
                        free(opt);
 
        char            my_exec_path[MAXPGPATH];
        char            env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")];  /* longer than
                                                                                                                                 * PGLOCALEDIR */
+       char       *dup_path;
 
        /* don't set LC_ALL in the backend */
        if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
                /* set for libpq to use */
                snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
                canonicalize_path(env_path + 12);
-               putenv(strdup(env_path));
+               dup_path = strdup(env_path);
+               if (dup_path)
+                       putenv(dup_path);
        }
 #endif
 
                /* set for libpq to use */
                snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
                canonicalize_path(env_path + 13);
-               putenv(strdup(env_path));
+               dup_path = strdup(env_path);
+               if (dup_path)
+                       putenv(dup_path);
        }
 }
 
 
        for (i = 0; i < testspec->nsessions; i++)
                nallsteps += testspec->sessions[i]->nsteps;
 
-       allsteps = malloc(nallsteps * sizeof(Step *));
+       allsteps = pg_malloc(nallsteps * sizeof(Step *));
 
        n = 0;
        for (i = 0; i < testspec->nsessions; i++)
                if (PQresultStatus(res) == PGRES_TUPLES_OK)
                {
                        if (PQntuples(res) == 1 && PQnfields(res) == 1)
-                               backend_pids[i] = strdup(PQgetvalue(res, 0, 0));
+                               backend_pids[i] = pg_strdup(PQgetvalue(res, 0, 0));
                        else
                        {
                                fprintf(stderr, "backend pid query returned %d rows and %d columns, expected 1 row and 1 column",
        for (i = 0; i < testspec->nsessions; i++)
                nsteps += testspec->sessions[i]->nsteps;
 
-       steps = malloc(sizeof(Step *) * nsteps);
+       steps = pg_malloc(sizeof(Step *) * nsteps);
 
        /*
         * To generate the permutations, we conceptually put the steps of each
         * A pile is actually just an integer which tells how many steps we've
         * already picked from this pile.
         */
-       piles = malloc(sizeof(int) * testspec->nsessions);
+       piles = pg_malloc(sizeof(int) * testspec->nsessions);
        for (i = 0; i < testspec->nsessions; i++)
                piles[i] = 0;
 
                Permutation *p = testspec->permutations[i];
                Step      **steps;
 
-               steps = malloc(p->nsteps * sizeof(Step *));
+               steps = pg_malloc(p->nsteps * sizeof(Step *));
 
                /* Find all the named steps using the lookup table */
                for (j = 0; j < p->nsteps; j++)
                return;
        }
 
-       waiting = malloc(sizeof(Step *) * testspec->nsessions);
-       errorstep = malloc(sizeof(Step *) * testspec->nsessions);
+       waiting = pg_malloc(sizeof(Step *) * testspec->nsessions);
+       errorstep = pg_malloc(sizeof(Step *) * testspec->nsessions);
 
        printf("\nstarting permutation:");
        for (i = 0; i < nsteps; i++)
 
                        }
                        | setup_list setup
                        {
-                               $$.elements = realloc($1.elements,
-                                                                         ($1.nelements + 1) * sizeof(void *));
+                               $$.elements = pg_realloc($1.elements,
+                                                                                ($1.nelements + 1) * sizeof(void *));
                                $$.elements[$1.nelements] = $2;
                                $$.nelements = $1.nelements + 1;
                        }
 session_list:
                        session_list session
                        {
-                               $$.elements = realloc($1.elements,
-                                                                         ($1.nelements + 1) * sizeof(void *));
+                               $$.elements = pg_realloc($1.elements,
+                                                                                ($1.nelements + 1) * sizeof(void *));
                                $$.elements[$1.nelements] = $2;
                                $$.nelements = $1.nelements + 1;
                        }
                        | session
                        {
                                $$.nelements = 1;
-                               $$.elements = malloc(sizeof(void *));
+                               $$.elements = pg_malloc(sizeof(void *));
                                $$.elements[0] = $1;
                        }
                ;
 session:
                        SESSION string_literal opt_setup step_list opt_teardown
                        {
-                               $$ = malloc(sizeof(Session));
+                               $$ = pg_malloc(sizeof(Session));
                                $$->name = $2;
                                $$->setupsql = $3;
                                $$->steps = (Step **) $4.elements;
 step_list:
                        step_list step
                        {
-                               $$.elements = realloc($1.elements,
-                                                                         ($1.nelements + 1) * sizeof(void *));
+                               $$.elements = pg_realloc($1.elements,
+                                                                                ($1.nelements + 1) * sizeof(void *));
                                $$.elements[$1.nelements] = $2;
                                $$.nelements = $1.nelements + 1;
                        }
                        | step
                        {
                                $$.nelements = 1;
-                               $$.elements = malloc(sizeof(void *));
+                               $$.elements = pg_malloc(sizeof(void *));
                                $$.elements[0] = $1;
                        }
                ;
 step:
                        STEP string_literal sqlblock
                        {
-                               $$ = malloc(sizeof(Step));
+                               $$ = pg_malloc(sizeof(Step));
                                $$->name = $2;
                                $$->sql = $3;
                                $$->errormsg = NULL;
 permutation_list:
                        permutation_list permutation
                        {
-                               $$.elements = realloc($1.elements,
-                                                                         ($1.nelements + 1) * sizeof(void *));
+                               $$.elements = pg_realloc($1.elements,
+                                                                                ($1.nelements + 1) * sizeof(void *));
                                $$.elements[$1.nelements] = $2;
                                $$.nelements = $1.nelements + 1;
                        }
                        | permutation
                        {
                                $$.nelements = 1;
-                               $$.elements = malloc(sizeof(void *));
+                               $$.elements = pg_malloc(sizeof(void *));
                                $$.elements[0] = $1;
                        }
                ;
 permutation:
                        PERMUTATION string_literal_list
                        {
-                               $$ = malloc(sizeof(Permutation));
+                               $$ = pg_malloc(sizeof(Permutation));
                                $$->stepnames = (char **) $2.elements;
                                $$->nsteps = $2.nelements;
                        }
 string_literal_list:
                        string_literal_list string_literal
                        {
-                               $$.elements = realloc($1.elements,
-                                                                         ($1.nelements + 1) * sizeof(void *));
+                               $$.elements = pg_realloc($1.elements,
+                                                                                ($1.nelements + 1) * sizeof(void *));
                                $$.elements[$1.nelements] = $2;
                                $$.nelements = $1.nelements + 1;
                        }
                        | string_literal
                        {
                                $$.nelements = 1;
-                               $$.elements = malloc(sizeof(void *));
+                               $$.elements = pg_malloc(sizeof(void *));
                                $$.elements[0] = $1;
                        }
                ;
 
                                }
 <qstr>\"               {
                                        litbuf[litbufpos] = '\0';
-                                       yylval.str = strdup(litbuf);
+                                       yylval.str = pg_strdup(litbuf);
                                        BEGIN(INITIAL);
                                        return(string_literal);
                                }
                                }
 <sql>{space}*"}" {
                                        litbuf[litbufpos] = '\0';
-                                       yylval.str = strdup(litbuf);
+                                       yylval.str = pg_strdup(litbuf);
                                        BEGIN(INITIAL);
                                        return(sqlblock);
                                }
 
 void
 add_stringlist_item(_stringlist **listhead, const char *str)
 {
-       _stringlist *newentry = malloc(sizeof(_stringlist));
+       _stringlist *newentry = pg_malloc(sizeof(_stringlist));
        _stringlist *oldentry;
 
-       newentry->str = strdup(str);
+       newentry->str = pg_strdup(str);
        newentry->next = NULL;
        if (*listhead == NULL)
                *listhead = newentry;
 static void
 split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
 {
-       char       *sc = strdup(s);
+       char       *sc = pg_strdup(s);
        char       *token = strtok(sc, delim);
 
        while (token)
 static const char *
 make_temp_sockdir(void)
 {
-       char       *template = strdup("/tmp/pg_regress-XXXXXX");
+       char       *template = pg_strdup("/tmp/pg_regress-XXXXXX");
 
        temp_sockdir = mkdtemp(template);
        if (temp_sockdir == NULL)
 
        while ((ptr = strstr(string, replace)) != NULL)
        {
-               char       *dup = strdup(string);
+               char       *dup = pg_strdup(string);
 
                strlcpy(string, dup, ptr - string + 1);
                strcat(string, replacement);
                 */
                if (string_matches_pattern(host_platform, platform))
                {
-                       _resultmap *entry = malloc(sizeof(_resultmap));
+                       _resultmap *entry = pg_malloc(sizeof(_resultmap));
 
-                       entry->test = strdup(buf);
-                       entry->type = strdup(file_type);
-                       entry->resultfile = strdup(expected);
+                       entry->test = pg_strdup(buf);
+                       entry->type = pg_strdup(file_type);
+                       entry->resultfile = pg_strdup(expected);
                        entry->next = resultmap;
                        resultmap = entry;
                }
                                progname, GetLastError());
                exit(2);
        }
-       tokenuser = malloc(retlen);
+       tokenuser = pg_malloc(retlen);
        if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
        {
                fprintf(stderr,
        int                     i;
 
 #ifdef WIN32
-       PID_TYPE   *active_pids = malloc(num_tests * sizeof(PID_TYPE));
+       PID_TYPE   *active_pids = pg_malloc(num_tests * sizeof(PID_TYPE));
 
        memcpy(active_pids, pids, num_tests * sizeof(PID_TYPE));
 #endif
 
        /* create the log file (copy of running status output) */
        snprintf(file, sizeof(file), "%s/regression.out", outputdir);
-       logfilename = strdup(file);
+       logfilename = pg_strdup(file);
        logfile = fopen(logfilename, "w");
        if (!logfile)
        {
 
        /* create the diffs file as empty */
        snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
-       difffilename = strdup(file);
+       difffilename = pg_strdup(file);
        difffile = fopen(difffilename, "w");
        if (!difffile)
        {
                                 * before we add the specified one.
                                 */
                                free_stringlist(&dblist);
-                               split_to_stringlist(strdup(optarg), ", ", &dblist);
+                               split_to_stringlist(pg_strdup(optarg), ", ", &dblist);
                                break;
                        case 2:
                                debug = true;
                                break;
                        case 3:
-                               inputdir = strdup(optarg);
+                               inputdir = pg_strdup(optarg);
                                break;
                        case 4:
                                add_stringlist_item(&loadlanguage, optarg);
                                max_connections = atoi(optarg);
                                break;
                        case 6:
-                               encoding = strdup(optarg);
+                               encoding = pg_strdup(optarg);
                                break;
                        case 7:
-                               outputdir = strdup(optarg);
+                               outputdir = pg_strdup(optarg);
                                break;
                        case 8:
                                add_stringlist_item(&schedulelist, optarg);
                                nolocale = true;
                                break;
                        case 13:
-                               hostname = strdup(optarg);
+                               hostname = pg_strdup(optarg);
                                break;
                        case 14:
                                port = atoi(optarg);
                                port_specified_by_user = true;
                                break;
                        case 15:
-                               user = strdup(optarg);
+                               user = pg_strdup(optarg);
                                break;
                        case 16:
                                /* "--bindir=" means to use PATH */
                                if (strlen(optarg))
-                                       bindir = strdup(optarg);
+                                       bindir = pg_strdup(optarg);
                                else
                                        bindir = NULL;
                                break;
                        case 17:
-                               dlpath = strdup(optarg);
+                               dlpath = pg_strdup(optarg);
                                break;
                        case 18:
-                               split_to_stringlist(strdup(optarg), ", ", &extraroles);
+                               split_to_stringlist(pg_strdup(optarg), ", ", &extraroles);
                                break;
                        case 19:
                                add_stringlist_item(&temp_configs, optarg);
                                use_existing = true;
                                break;
                        case 21:
-                               launcher = strdup(optarg);
+                               launcher = pg_strdup(optarg);
                                break;
                        case 22:
                                add_stringlist_item(&loadextension, optarg);
                                break;
                        case 24:
-                               config_auth_datadir = pstrdup(optarg);
+                               config_auth_datadir = pg_strdup(optarg);
                                break;
                        default:
                                /* getopt_long already emitted a complaint */