Use palloc_object() and palloc_array() in backend code
authorMichael Paquier <[email protected]>
Tue, 9 Dec 2025 22:36:46 +0000 (07:36 +0900)
committerMichael Paquier <[email protected]>
Tue, 9 Dec 2025 22:36:46 +0000 (07:36 +0900)
The idea is to encourage more the use of these new routines across the
tree, as these offer stronger type safety guarantees than palloc().
This batch of changes includes most of the trivial changes suggested by
the author for src/backend/.

A total of 334 files are updated here.  Among these files, 48 of them
have their build change slightly; these are caused by line number
changes as the new allocation formulas are simpler, shaving around 100
lines of code in total.

Similar work has been done in 0c3c5c3b06a3 and 31d3847a37be.

Author: David Geier <[email protected]>
Discussion: https://postgr.es/m/ad0748d4-3080-436e-b0bc-ac8f86a3466a@gmail.com

333 files changed:
src/backend/access/brin/brin.c
src/backend/access/brin/brin_minmax_multi.c
src/backend/access/brin/brin_revmap.c
src/backend/access/brin/brin_tuple.c
src/backend/access/common/attmap.c
src/backend/access/common/heaptuple.c
src/backend/access/common/printtup.c
src/backend/access/common/reloptions.c
src/backend/access/common/tidstore.c
src/backend/access/common/toast_internals.c
src/backend/access/common/tupconvert.c
src/backend/access/common/tupdesc.c
src/backend/access/gin/ginbtree.c
src/backend/access/gin/ginbulk.c
src/backend/access/gin/gindatapage.c
src/backend/access/gin/ginentrypage.c
src/backend/access/gin/ginget.c
src/backend/access/gin/gininsert.c
src/backend/access/gin/ginscan.c
src/backend/access/gin/ginutil.c
src/backend/access/gin/ginvacuum.c
src/backend/access/gist/gist.c
src/backend/access/gist/gistbuild.c
src/backend/access/gist/gistbuildbuffers.c
src/backend/access/gist/gistproc.c
src/backend/access/gist/gistscan.c
src/backend/access/gist/gistsplit.c
src/backend/access/gist/gistutil.c
src/backend/access/gist/gistvacuum.c
src/backend/access/hash/hash.c
src/backend/access/hash/hashsort.c
src/backend/access/heap/heapam.c
src/backend/access/heap/heapam_handler.c
src/backend/access/heap/rewriteheap.c
src/backend/access/heap/vacuumlazy.c
src/backend/access/index/amvalidate.c
src/backend/access/index/genam.c
src/backend/access/nbtree/nbtdedup.c
src/backend/access/nbtree/nbtinsert.c
src/backend/access/nbtree/nbtpage.c
src/backend/access/nbtree/nbtree.c
src/backend/access/nbtree/nbtsearch.c
src/backend/access/nbtree/nbtsort.c
src/backend/access/nbtree/nbtsplitloc.c
src/backend/access/nbtree/nbtxlog.c
src/backend/access/spgist/spgdoinsert.c
src/backend/access/spgist/spginsert.c
src/backend/access/spgist/spgkdtreeproc.c
src/backend/access/spgist/spgproc.c
src/backend/access/spgist/spgquadtreeproc.c
src/backend/access/spgist/spgscan.c
src/backend/access/spgist/spgtextproc.c
src/backend/access/spgist/spgutils.c
src/backend/access/spgist/spgvacuum.c
src/backend/access/spgist/spgxlog.c
src/backend/access/tablesample/system.c
src/backend/access/transam/multixact.c
src/backend/access/transam/parallel.c
src/backend/access/transam/timeline.c
src/backend/access/transam/twophase.c
src/backend/access/transam/xact.c
src/backend/access/transam/xlog.c
src/backend/access/transam/xlogfuncs.c
src/backend/access/transam/xlogprefetcher.c
src/backend/access/transam/xlogrecovery.c
src/backend/access/transam/xlogutils.c
src/backend/backup/basebackup.c
src/backend/backup/basebackup_copy.c
src/backend/backup/basebackup_gzip.c
src/backend/backup/basebackup_incremental.c
src/backend/backup/basebackup_lz4.c
src/backend/backup/basebackup_progress.c
src/backend/backup/basebackup_server.c
src/backend/backup/basebackup_target.c
src/backend/backup/basebackup_throttle.c
src/backend/backup/basebackup_zstd.c
src/backend/backup/walsummary.c
src/backend/bootstrap/bootstrap.c
src/backend/catalog/dependency.c
src/backend/catalog/heap.c
src/backend/catalog/index.c
src/backend/catalog/namespace.c
src/backend/catalog/objectaddress.c
src/backend/catalog/pg_constraint.c
src/backend/catalog/pg_depend.c
src/backend/catalog/pg_enum.c
src/backend/catalog/pg_publication.c
src/backend/catalog/pg_shdepend.c
src/backend/catalog/pg_subscription.c
src/backend/catalog/storage.c
src/backend/commands/analyze.c
src/backend/commands/cluster.c
src/backend/commands/copy.c
src/backend/commands/copyfrom.c
src/backend/commands/copyto.c
src/backend/commands/createas.c
src/backend/commands/dbcommands.c
src/backend/commands/event_trigger.c
src/backend/commands/explain.c
src/backend/commands/explain_dr.c
src/backend/commands/explain_state.c
src/backend/commands/extension.c
src/backend/commands/functioncmds.c
src/backend/commands/matview.c
src/backend/commands/opclasscmds.c
src/backend/commands/policy.c
src/backend/commands/publicationcmds.c
src/backend/commands/seclabel.c
src/backend/commands/subscriptioncmds.c
src/backend/commands/tablecmds.c
src/backend/commands/trigger.c
src/backend/commands/tsearchcmds.c
src/backend/commands/typecmds.c
src/backend/commands/user.c
src/backend/commands/vacuumparallel.c
src/backend/executor/execExpr.c
src/backend/executor/execGrouping.c
src/backend/executor/execIndexing.c
src/backend/executor/execMain.c
src/backend/executor/execParallel.c
src/backend/executor/execReplication.c
src/backend/executor/execTuples.c
src/backend/executor/functions.c
src/backend/executor/nodeAgg.c
src/backend/executor/nodeAppend.c
src/backend/executor/nodeFunctionscan.c
src/backend/executor/nodeGatherMerge.c
src/backend/executor/nodeHashjoin.c
src/backend/executor/nodeIndexonlyscan.c
src/backend/executor/nodeIndexscan.c
src/backend/executor/nodeMemoize.c
src/backend/executor/nodeMergeAppend.c
src/backend/executor/nodeModifyTable.c
src/backend/executor/nodeProjectSet.c
src/backend/executor/nodeSamplescan.c
src/backend/executor/nodeTableFuncscan.c
src/backend/executor/nodeTidrangescan.c
src/backend/executor/nodeTidscan.c
src/backend/executor/nodeWindowAgg.c
src/backend/executor/spi.c
src/backend/executor/tqueue.c
src/backend/executor/tstoreReceiver.c
src/backend/foreign/foreign.c
src/backend/jit/llvm/llvmjit.c
src/backend/jit/llvm/llvmjit_deform.c
src/backend/jit/llvm/llvmjit_expr.c
src/backend/lib/bipartite_match.c
src/backend/lib/dshash.c
src/backend/lib/integerset.c
src/backend/lib/pairingheap.c
src/backend/lib/rbtree.c
src/backend/libpq/auth-oauth.c
src/backend/libpq/auth-scram.c
src/backend/libpq/hba.c
src/backend/libpq/pqcomm.c
src/backend/nodes/nodeFuncs.c
src/backend/nodes/queryjumblefuncs.c
src/backend/nodes/tidbitmap.c
src/backend/optimizer/geqo/geqo_erx.c
src/backend/optimizer/geqo/geqo_eval.c
src/backend/optimizer/geqo/geqo_pmx.c
src/backend/optimizer/geqo/geqo_pool.c
src/backend/optimizer/geqo/geqo_recombination.c
src/backend/optimizer/path/clausesel.c
src/backend/optimizer/path/costsize.c
src/backend/optimizer/path/indxpath.c
src/backend/optimizer/path/joinrels.c
src/backend/optimizer/plan/analyzejoins.c
src/backend/optimizer/plan/createplan.c
src/backend/optimizer/plan/initsplan.c
src/backend/optimizer/plan/planagg.c
src/backend/optimizer/plan/planner.c
src/backend/optimizer/plan/setrefs.c
src/backend/optimizer/prep/prepjointree.c
src/backend/optimizer/prep/prepunion.c
src/backend/optimizer/util/appendinfo.c
src/backend/optimizer/util/clauses.c
src/backend/optimizer/util/extendplan.c
src/backend/optimizer/util/plancat.c
src/backend/optimizer/util/predtest.c
src/backend/optimizer/util/relnode.c
src/backend/optimizer/util/tlist.c
src/backend/parser/analyze.c
src/backend/parser/gram.y
src/backend/parser/parse_clause.c
src/backend/parser/parse_expr.c
src/backend/parser/parse_node.c
src/backend/parser/parse_param.c
src/backend/parser/parse_relation.c
src/backend/parser/parse_type.c
src/backend/partitioning/partbounds.c
src/backend/partitioning/partdesc.c
src/backend/postmaster/autovacuum.c
src/backend/postmaster/bgworker.c
src/backend/postmaster/checkpointer.c
src/backend/postmaster/launch_backend.c
src/backend/postmaster/pgarch.c
src/backend/postmaster/postmaster.c
src/backend/postmaster/syslogger.c
src/backend/postmaster/walsummarizer.c
src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
src/backend/replication/logical/applyparallelworker.c
src/backend/replication/logical/launcher.c
src/backend/replication/logical/logical.c
src/backend/replication/logical/logicalfuncs.c
src/backend/replication/logical/proto.c
src/backend/replication/logical/relation.c
src/backend/replication/logical/reorderbuffer.c
src/backend/replication/logical/slotsync.c
src/backend/replication/logical/snapbuild.c
src/backend/replication/logical/syncutils.c
src/backend/replication/logical/worker.c
src/backend/replication/pgoutput/pgoutput.c
src/backend/replication/syncrep.c
src/backend/replication/walreceiver.c
src/backend/replication/walsender.c
src/backend/rewrite/rewriteHandler.c
src/backend/rewrite/rewriteManip.c
src/backend/snowball/dict_snowball.c
src/backend/statistics/dependencies.c
src/backend/statistics/extended_stats.c
src/backend/statistics/mcv.c
src/backend/storage/file/buffile.c
src/backend/storage/ipc/procarray.c
src/backend/storage/ipc/shm_mq.c
src/backend/storage/ipc/shmem.c
src/backend/storage/lmgr/lock.c
src/backend/storage/lmgr/predicate.c
src/backend/storage/smgr/bulk_write.c
src/backend/storage/smgr/md.c
src/backend/storage/smgr/smgr.c
src/backend/storage/sync/sync.c
src/backend/tcop/pquery.c
src/backend/tsearch/dict.c
src/backend/tsearch/dict_ispell.c
src/backend/tsearch/dict_simple.c
src/backend/tsearch/dict_synonym.c
src/backend/tsearch/dict_thesaurus.c
src/backend/tsearch/spell.c
src/backend/tsearch/to_tsany.c
src/backend/tsearch/ts_parse.c
src/backend/tsearch/ts_selfuncs.c
src/backend/tsearch/ts_typanalyze.c
src/backend/tsearch/ts_utils.c
src/backend/tsearch/wparser.c
src/backend/tsearch/wparser_def.c
src/backend/utils/activity/pgstat_relation.c
src/backend/utils/activity/wait_event.c
src/backend/utils/adt/acl.c
src/backend/utils/adt/array_selfuncs.c
src/backend/utils/adt/array_typanalyze.c
src/backend/utils/adt/array_userfuncs.c
src/backend/utils/adt/arrayfuncs.c
src/backend/utils/adt/arraysubs.c
src/backend/utils/adt/date.c
src/backend/utils/adt/datetime.c
src/backend/utils/adt/formatting.c
src/backend/utils/adt/geo_ops.c
src/backend/utils/adt/geo_spgist.c
src/backend/utils/adt/int.c
src/backend/utils/adt/int8.c
src/backend/utils/adt/json.c
src/backend/utils/adt/jsonb_gin.c
src/backend/utils/adt/jsonb_util.c
src/backend/utils/adt/jsonfuncs.c
src/backend/utils/adt/jsonpath_exec.c
src/backend/utils/adt/jsonpath_gram.y
src/backend/utils/adt/lockfuncs.c
src/backend/utils/adt/mac.c
src/backend/utils/adt/mac8.c
src/backend/utils/adt/mcxtfuncs.c
src/backend/utils/adt/misc.c
src/backend/utils/adt/multirangetypes.c
src/backend/utils/adt/multirangetypes_selfuncs.c
src/backend/utils/adt/multixactfuncs.c
src/backend/utils/adt/network.c
src/backend/utils/adt/network_gist.c
src/backend/utils/adt/network_spgist.c
src/backend/utils/adt/numeric.c
src/backend/utils/adt/orderedsetaggs.c
src/backend/utils/adt/pg_locale_libc.c
src/backend/utils/adt/pg_ndistinct.c
src/backend/utils/adt/rangetypes.c
src/backend/utils/adt/rangetypes_gist.c
src/backend/utils/adt/rangetypes_selfuncs.c
src/backend/utils/adt/rangetypes_spgist.c
src/backend/utils/adt/rangetypes_typanalyze.c
src/backend/utils/adt/regexp.c
src/backend/utils/adt/rowtypes.c
src/backend/utils/adt/ruleutils.c
src/backend/utils/adt/selfuncs.c
src/backend/utils/adt/skipsupport.c
src/backend/utils/adt/tid.c
src/backend/utils/adt/timestamp.c
src/backend/utils/adt/tsginidx.c
src/backend/utils/adt/tsgistidx.c
src/backend/utils/adt/tsquery.c
src/backend/utils/adt/tsquery_cleanup.c
src/backend/utils/adt/tsquery_gist.c
src/backend/utils/adt/tsquery_op.c
src/backend/utils/adt/tsquery_util.c
src/backend/utils/adt/tsrank.c
src/backend/utils/adt/tsvector.c
src/backend/utils/adt/tsvector_op.c
src/backend/utils/adt/tsvector_parser.c
src/backend/utils/adt/uuid.c
src/backend/utils/adt/varlena.c
src/backend/utils/adt/xml.c
src/backend/utils/cache/catcache.c
src/backend/utils/cache/evtcache.c
src/backend/utils/cache/inval.c
src/backend/utils/cache/lsyscache.c
src/backend/utils/cache/partcache.c
src/backend/utils/cache/plancache.c
src/backend/utils/cache/relcache.c
src/backend/utils/cache/typcache.c
src/backend/utils/error/elog.c
src/backend/utils/fmgr/funcapi.c
src/backend/utils/init/postinit.c
src/backend/utils/mb/mbutils.c
src/backend/utils/misc/conffiles.c
src/backend/utils/misc/guc-file.l
src/backend/utils/misc/guc.c
src/backend/utils/misc/injection_point.c
src/backend/utils/misc/queryenvironment.c
src/backend/utils/misc/tzparser.c
src/backend/utils/mmgr/dsa.c
src/backend/utils/sort/logtape.c
src/backend/utils/sort/sharedtuplestore.c
src/backend/utils/sort/tuplesort.c
src/backend/utils/sort/tuplesortvariants.c
src/backend/utils/sort/tuplestore.c
src/backend/utils/time/snapmgr.c

index cb3331921cbfdae30e116be3f2bd676cf426d981..26cb75058d19126682ea3f7cd9689e8f8b3f2567 100644 (file)
@@ -318,7 +318,7 @@ initialize_brin_insertstate(Relation idxRel, IndexInfo *indexInfo)
    MemoryContext oldcxt;
 
    oldcxt = MemoryContextSwitchTo(indexInfo->ii_Context);
-   bistate = palloc0(sizeof(BrinInsertState));
+   bistate = palloc0_object(BrinInsertState);
    bistate->bis_desc = brin_build_desc(idxRel);
    bistate->bis_rmAccess = brinRevmapInitialize(idxRel,
                                                 &bistate->bis_pages_per_range);
@@ -1185,7 +1185,7 @@ brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    {
        SortCoordinate coordinate;
 
-       coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+       coordinate = palloc0_object(SortCoordinateData);
        coordinate->isWorker = false;
        coordinate->nParticipants =
            state->bs_leader->nparticipanttuplesorts;
@@ -2384,7 +2384,7 @@ _brin_begin_parallel(BrinBuildState *buildstate, Relation heap, Relation index,
    Size        estsort;
    BrinShared *brinshared;
    Sharedsort *sharedsort;
-   BrinLeader *brinleader = (BrinLeader *) palloc0(sizeof(BrinLeader));
+   BrinLeader *brinleader = palloc0_object(BrinLeader);
    WalUsage   *walusage;
    BufferUsage *bufferusage;
    bool        leaderparticipates = true;
@@ -2828,7 +2828,7 @@ _brin_parallel_scan_and_build(BrinBuildState *state,
    IndexInfo  *indexInfo;
 
    /* Initialize local tuplesort coordination state */
-   coordinate = palloc0(sizeof(SortCoordinateData));
+   coordinate = palloc0_object(SortCoordinateData);
    coordinate->isWorker = true;
    coordinate->nParticipants = -1;
    coordinate->sharedsort = sharedsort;
index f8a11444d669f5009d631fdee4df96089e8e2cc6..0298a9da8ba7479d342a68e83eee6a8ca787cb2a 100644 (file)
@@ -1340,7 +1340,7 @@ build_distances(FmgrInfo *distanceFn, Oid colloid,
        return NULL;
 
    ndistances = (neranges - 1);
-   distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
+   distances = palloc0_array(DistanceValue, ndistances);
 
    /*
     * Walk through the ranges once and compute the distance between the
@@ -1504,7 +1504,7 @@ reduce_expanded_ranges(ExpandedRange *eranges, int neranges,
 
    /* allocate space for the boundary values */
    nvalues = 0;
-   values = (Datum *) palloc(sizeof(Datum) * max_values);
+   values = palloc_array(Datum, max_values);
 
    /* add the global min/max values, from the first/last range */
    values[nvalues++] = eranges[0].minval;
index 4e380ecc71097c29504de77757ffa1bfc517096e..644f9889a8aec57e799ea8c42706e39f21390fbf 100644 (file)
@@ -79,7 +79,7 @@ brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange)
    page = BufferGetPage(meta);
    metadata = (BrinMetaPageData *) PageGetContents(page);
 
-   revmap = palloc(sizeof(BrinRevmap));
+   revmap = palloc_object(BrinRevmap);
    revmap->rm_irel = idxrel;
    revmap->rm_pagesPerRange = metadata->pagesPerRange;
    revmap->rm_lastRevmapPage = metadata->lastRevmapPage;
index 861f397e6db58e75a518c6fcb9fcf08123826daf..43850ce8f48c5dfcf382a6455b3ef6916a874d2f 100644 (file)
@@ -119,13 +119,12 @@ brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple,
 
    Assert(brdesc->bd_totalstored > 0);
 
-   values = (Datum *) palloc(sizeof(Datum) * brdesc->bd_totalstored);
-   nulls = (bool *) palloc0(sizeof(bool) * brdesc->bd_totalstored);
-   phony_nullbitmap = (bits8 *)
-       palloc(sizeof(bits8) * BITMAPLEN(brdesc->bd_totalstored));
+   values = palloc_array(Datum, brdesc->bd_totalstored);
+   nulls = palloc0_array(bool, brdesc->bd_totalstored);
+   phony_nullbitmap = palloc_array(bits8, BITMAPLEN(brdesc->bd_totalstored));
 
 #ifdef TOAST_INDEX_HACK
-   untoasted_values = (Datum *) palloc(sizeof(Datum) * brdesc->bd_totalstored);
+   untoasted_values = palloc_array(Datum, brdesc->bd_totalstored);
 #endif
 
    /*
@@ -488,9 +487,9 @@ brin_new_memtuple(BrinDesc *brdesc)
                        sizeof(BrinValues) * brdesc->bd_tupdesc->natts);
    dtup = palloc0(basesize + sizeof(Datum) * brdesc->bd_totalstored);
 
-   dtup->bt_values = palloc(sizeof(Datum) * brdesc->bd_totalstored);
-   dtup->bt_allnulls = palloc(sizeof(bool) * brdesc->bd_tupdesc->natts);
-   dtup->bt_hasnulls = palloc(sizeof(bool) * brdesc->bd_tupdesc->natts);
+   dtup->bt_values = palloc_array(Datum, brdesc->bd_totalstored);
+   dtup->bt_allnulls = palloc_array(bool, brdesc->bd_tupdesc->natts);
+   dtup->bt_hasnulls = palloc_array(bool, brdesc->bd_tupdesc->natts);
 
    dtup->bt_empty_range = true;
 
index 4901ebecef73f2a66e06eaa3999998a5edbb06fd..4cfa9ee78f99042b3a70409bcf1e4f6f47f24cf7 100644 (file)
@@ -41,9 +41,9 @@ make_attrmap(int maplen)
 {
    AttrMap    *res;
 
-   res = (AttrMap *) palloc0(sizeof(AttrMap));
+   res = palloc0_object(AttrMap);
    res->maplen = maplen;
-   res->attnums = (AttrNumber *) palloc0(sizeof(AttrNumber) * maplen);
+   res->attnums = palloc0_array(AttrNumber, maplen);
    return res;
 }
 
index 1967b047020a6d938c5e82cffd31c89fa67bdacd..b7820d692e2ea581dfa6e0e9296c6bd8b8bd13b8 100644 (file)
@@ -1230,8 +1230,8 @@ heap_modify_tuple(HeapTuple tuple,
     * O(N^2) if there are many non-replaced columns, so it seems better to
     * err on the side of linear cost.
     */
-   values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
-   isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
+   values = palloc_array(Datum, numberOfAttributes);
+   isnull = palloc_array(bool, numberOfAttributes);
 
    heap_deform_tuple(tuple, tupleDesc, values, isnull);
 
@@ -1292,8 +1292,8 @@ heap_modify_tuple_by_cols(HeapTuple tuple,
     * allocate and fill values and isnull arrays from the tuple, then replace
     * selected columns from the input arrays.
     */
-   values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
-   isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
+   values = palloc_array(Datum, numberOfAttributes);
+   isnull = palloc_array(bool, numberOfAttributes);
 
    heap_deform_tuple(tuple, tupleDesc, values, isnull);
 
index 025fe75916f3086c4412c2fdd42d84b53702b868..47b2b2d2335cc7f489b9cb557306694510adee08 100644 (file)
@@ -71,7 +71,7 @@ typedef struct
 DestReceiver *
 printtup_create_DR(CommandDest dest)
 {
-   DR_printtup *self = (DR_printtup *) palloc0(sizeof(DR_printtup));
+   DR_printtup *self = palloc0_object(DR_printtup);
 
    self->pub.receiveSlot = printtup;   /* might get changed later */
    self->pub.rStartup = printtup_startup;
index 9e288dfecbfd01876b616ab0387b06c7f5031169..31926d8a368aebdc2b67009e2dc35db5714acc7b 100644 (file)
@@ -776,7 +776,7 @@ register_reloptions_validator(local_relopts *relopts, relopts_validator validato
 static void
 add_local_reloption(local_relopts *relopts, relopt_gen *newoption, int offset)
 {
-   local_relopt *opt = palloc(sizeof(*opt));
+   local_relopt *opt = palloc_object(local_relopt);
 
    Assert(offset < relopts->relopt_struct_size);
 
@@ -1570,7 +1570,7 @@ static relopt_value *
 parseLocalRelOptions(local_relopts *relopts, Datum options, bool validate)
 {
    int         nopts = list_length(relopts->options);
-   relopt_value *values = palloc(sizeof(*values) * nopts);
+   relopt_value *values = palloc_array(relopt_value, nopts);
    ListCell   *lc;
    int         i = 0;
 
@@ -1991,7 +1991,7 @@ void *
 build_local_reloptions(local_relopts *relopts, Datum options, bool validate)
 {
    int         noptions = list_length(relopts->options);
-   relopt_parse_elt *elems = palloc(sizeof(*elems) * noptions);
+   relopt_parse_elt *elems = palloc_array(relopt_parse_elt, noptions);
    relopt_value *vals;
    void       *opts;
    int         i = 0;
index fb807d9fe5929407aff27fad1e10131bc4f60a8c..6fae41e7b6d196d9d6762da906cd35a77a15f06f 100644 (file)
@@ -166,7 +166,7 @@ TidStoreCreateLocal(size_t max_bytes, bool insert_only)
    size_t      minContextSize = ALLOCSET_DEFAULT_MINSIZE;
    size_t      maxBlockSize = ALLOCSET_DEFAULT_MAXSIZE;
 
-   ts = palloc0(sizeof(TidStore));
+   ts = palloc0_object(TidStore);
 
    /* choose the maxBlockSize to be no larger than 1/16 of max_bytes */
    while (16 * maxBlockSize > max_bytes)
@@ -212,7 +212,7 @@ TidStoreCreateShared(size_t max_bytes, int tranche_id)
    size_t      dsa_init_size = DSA_DEFAULT_INIT_SEGMENT_SIZE;
    size_t      dsa_max_size = DSA_MAX_SEGMENT_SIZE;
 
-   ts = palloc0(sizeof(TidStore));
+   ts = palloc0_object(TidStore);
 
    /*
     * Choose the initial and maximum DSA segment sizes to be no longer than
@@ -250,7 +250,7 @@ TidStoreAttach(dsa_handle area_handle, dsa_pointer handle)
    Assert(DsaPointerIsValid(handle));
 
    /* create per-backend state */
-   ts = palloc0(sizeof(TidStore));
+   ts = palloc0_object(TidStore);
 
    area = dsa_attach(area_handle);
 
@@ -472,7 +472,7 @@ TidStoreBeginIterate(TidStore *ts)
 {
    TidStoreIter *iter;
 
-   iter = palloc0(sizeof(TidStoreIter));
+   iter = palloc0_object(TidStoreIter);
    iter->ts = ts;
 
    if (TidStoreIsShared(ts))
index 63b848473f8a67c5dac55f66794761325582c44e..d06af82de15d92abc35fada6f710a50b41954349 100644 (file)
@@ -568,7 +568,7 @@ toast_open_indexes(Relation toastrel,
    *num_indexes = list_length(indexlist);
 
    /* Open all the index relations */
-   *toastidxs = (Relation *) palloc(*num_indexes * sizeof(Relation));
+   *toastidxs = palloc_array(Relation, *num_indexes);
    foreach(lc, indexlist)
        (*toastidxs)[i++] = index_open(lfirst_oid(lc), lock);
 
index 1df0c2d2f98fafab8cb341b855c5ebeefafc25bd..99c197e361f68623d0db0fa3d5e396fc257df0c0 100644 (file)
@@ -75,17 +75,17 @@ convert_tuples_by_position(TupleDesc indesc,
    }
 
    /* Prepare the map structure */
-   map = (TupleConversionMap *) palloc(sizeof(TupleConversionMap));
+   map = palloc_object(TupleConversionMap);
    map->indesc = indesc;
    map->outdesc = outdesc;
    map->attrMap = attrMap;
    /* preallocate workspace for Datum arrays */
    n = outdesc->natts + 1;     /* +1 for NULL */
-   map->outvalues = (Datum *) palloc(n * sizeof(Datum));
-   map->outisnull = (bool *) palloc(n * sizeof(bool));
+   map->outvalues = palloc_array(Datum, n);
+   map->outisnull = palloc_array(bool, n);
    n = indesc->natts + 1;      /* +1 for NULL */
-   map->invalues = (Datum *) palloc(n * sizeof(Datum));
-   map->inisnull = (bool *) palloc(n * sizeof(bool));
+   map->invalues = palloc_array(Datum, n);
+   map->inisnull = palloc_array(bool, n);
    map->invalues[0] = (Datum) 0;   /* set up the NULL entry */
    map->inisnull[0] = true;
 
@@ -132,16 +132,16 @@ convert_tuples_by_name_attrmap(TupleDesc indesc,
    Assert(attrMap != NULL);
 
    /* Prepare the map structure */
-   map = (TupleConversionMap *) palloc(sizeof(TupleConversionMap));
+   map = palloc_object(TupleConversionMap);
    map->indesc = indesc;
    map->outdesc = outdesc;
    map->attrMap = attrMap;
    /* preallocate workspace for Datum arrays */
-   map->outvalues = (Datum *) palloc(n * sizeof(Datum));
-   map->outisnull = (bool *) palloc(n * sizeof(bool));
+   map->outvalues = palloc_array(Datum, n);
+   map->outisnull = palloc_array(bool, n);
    n = indesc->natts + 1;      /* +1 for NULL */
-   map->invalues = (Datum *) palloc(n * sizeof(Datum));
-   map->inisnull = (bool *) palloc(n * sizeof(bool));
+   map->invalues = palloc_array(Datum, n);
+   map->inisnull = palloc_array(bool, n);
    map->invalues[0] = (Datum) 0;   /* set up the NULL entry */
    map->inisnull[0] = true;
 
index d715c345dd84a9c953409f154e849d154341f622..bcd1ddcc68b438a550dbc8ed9a11adbdf93da2b5 100644 (file)
@@ -361,7 +361,7 @@ CreateTupleDescCopyConstr(TupleDesc tupdesc)
    /* Copy the TupleConstr data structure, if any */
    if (constr)
    {
-       TupleConstr *cpy = (TupleConstr *) palloc0(sizeof(TupleConstr));
+       TupleConstr *cpy = palloc0_object(TupleConstr);
 
        cpy->has_not_null = constr->has_not_null;
        cpy->has_generated_stored = constr->has_generated_stored;
index 644d484ea53c6b62cdc30f9f1c3cdd436bc60e1f..47f881ae5968524af83a26eaa3fdad663dd70863 100644 (file)
@@ -85,7 +85,7 @@ ginFindLeafPage(GinBtree btree, bool searchMode,
 {
    GinBtreeStack *stack;
 
-   stack = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+   stack = palloc_object(GinBtreeStack);
    stack->blkno = btree->rootBlkno;
    stack->buffer = ReadBuffer(btree->index, btree->rootBlkno);
    stack->parent = NULL;
@@ -152,7 +152,7 @@ ginFindLeafPage(GinBtree btree, bool searchMode,
        }
        else
        {
-           GinBtreeStack *ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+           GinBtreeStack *ptr = palloc_object(GinBtreeStack);
 
            ptr->parent = stack;
            stack = ptr;
@@ -246,7 +246,7 @@ ginFindParents(GinBtree btree, GinBtreeStack *stack)
    blkno = root->blkno;
    buffer = root->buffer;
 
-   ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+   ptr = palloc_object(GinBtreeStack);
 
    for (;;)
    {
index 302cb2092a9a8c19b13e1ab62650574c440ad4b1..f73ee7b1fa4bab3fb4af5b34bf1452b7d522f4cc 100644 (file)
@@ -93,7 +93,7 @@ ginAllocEntryAccumulator(void *arg)
     */
    if (accum->entryallocator == NULL || accum->eas_used >= DEF_NENTRY)
    {
-       accum->entryallocator = palloc(sizeof(GinEntryAccumulator) * DEF_NENTRY);
+       accum->entryallocator = palloc_array(GinEntryAccumulator, DEF_NENTRY);
        accum->allocatedMemory += GetMemoryChunkSpace(accum->entryallocator);
        accum->eas_used = 0;
    }
@@ -177,8 +177,7 @@ ginInsertBAEntry(BuildAccumulator *accum,
        ea->maxcount = DEF_NPTR;
        ea->count = 1;
        ea->shouldSort = false;
-       ea->list =
-           (ItemPointerData *) palloc(sizeof(ItemPointerData) * DEF_NPTR);
+       ea->list = palloc_array(ItemPointerData, DEF_NPTR);
        ea->list[0] = *heapptr;
        accum->allocatedMemory += GetMemoryChunkSpace(ea->list);
    }
index 8d9e3727c518d70d588df11f31624299f1a01b27..0140bd4904b247345c03b63f79f693c34801f1ec 100644 (file)
@@ -1332,7 +1332,7 @@ dataSplitPageInternal(GinBtree btree, Buffer origbuf,
 static void *
 dataPrepareDownlink(GinBtree btree, Buffer lbuf)
 {
-   PostingItem *pitem = palloc(sizeof(PostingItem));
+   PostingItem *pitem = palloc_object(PostingItem);
    Page        lpage = BufferGetPage(lbuf);
 
    PostingItemSetBlockNumber(pitem, BufferGetBlockNumber(lbuf));
@@ -1374,7 +1374,7 @@ disassembleLeaf(Page page)
    char       *segbegin;
    char       *segend;
 
-   leaf = palloc0(sizeof(disassembledLeaf));
+   leaf = palloc0_object(disassembledLeaf);
    dlist_init(&leaf->segments);
 
    if (GinPageIsCompressed(page))
@@ -1387,7 +1387,7 @@ disassembleLeaf(Page page)
        segend = segbegin + GinDataLeafPageGetPostingListSize(page);
        while ((char *) seg < segend)
        {
-           leafSegmentInfo *seginfo = palloc(sizeof(leafSegmentInfo));
+           leafSegmentInfo *seginfo = palloc_object(leafSegmentInfo);
 
            seginfo->action = GIN_SEGMENT_UNMODIFIED;
            seginfo->seg = seg;
@@ -1414,7 +1414,7 @@ disassembleLeaf(Page page)
 
        if (nuncompressed > 0)
        {
-           seginfo = palloc(sizeof(leafSegmentInfo));
+           seginfo = palloc_object(leafSegmentInfo);
 
            seginfo->action = GIN_SEGMENT_REPLACE;
            seginfo->seg = NULL;
@@ -1455,7 +1455,7 @@ addItemsToLeaf(disassembledLeaf *leaf, ItemPointer newItems, int nNewItems)
     */
    if (dlist_is_empty(&leaf->segments))
    {
-       newseg = palloc(sizeof(leafSegmentInfo));
+       newseg = palloc_object(leafSegmentInfo);
        newseg->seg = NULL;
        newseg->items = newItems;
        newseg->nitems = nNewItems;
@@ -1512,7 +1512,7 @@ addItemsToLeaf(disassembledLeaf *leaf, ItemPointer newItems, int nNewItems)
            cur->seg != NULL &&
            SizeOfGinPostingList(cur->seg) >= GinPostingListSegmentTargetSize)
        {
-           newseg = palloc(sizeof(leafSegmentInfo));
+           newseg = palloc_object(leafSegmentInfo);
            newseg->seg = NULL;
            newseg->items = nextnew;
            newseg->nitems = nthis;
@@ -1629,7 +1629,7 @@ leafRepackItems(disassembledLeaf *leaf, ItemPointer remaining)
                    if (seginfo->action != GIN_SEGMENT_INSERT)
                        seginfo->action = GIN_SEGMENT_REPLACE;
 
-                   nextseg = palloc(sizeof(leafSegmentInfo));
+                   nextseg = palloc_object(leafSegmentInfo);
                    nextseg->action = GIN_SEGMENT_INSERT;
                    nextseg->seg = NULL;
                    nextseg->items = &seginfo->items[npacked];
index 94f49d72a9859b9fdd42cfb2941b617fde419f1e..23a41ce9486b1443fa76252ae49a11ae8c8651f6 100644 (file)
@@ -183,7 +183,7 @@ ginReadTuple(GinState *ginstate, OffsetNumber attnum, IndexTuple itup,
    }
    else
    {
-       ipd = (ItemPointer) palloc(sizeof(ItemPointerData) * nipd);
+       ipd = palloc_array(ItemPointerData, nipd);
        memcpy(ipd, ptr, sizeof(ItemPointerData) * nipd);
    }
    *nitems = nipd;
@@ -708,7 +708,7 @@ entryPrepareDownlink(GinBtree btree, Buffer lbuf)
 
    itup = getRightMostTuple(lpage);
 
-   insertData = palloc(sizeof(GinBtreeEntryInsertData));
+   insertData = palloc_object(GinBtreeEntryInsertData);
    insertData->entry = GinFormInteriorTuple(itup, lpage, lblkno);
    insertData->isDelete = false;
 
index 0d4108d05a38ff6b865455a9c6221e29cfa94cbc..b3e2e9d5f6e308dcbb09e5e27728c52df49cb284 100644 (file)
@@ -552,7 +552,7 @@ startScanKey(GinState *ginstate, GinScanOpaque so, GinScanKey key)
    {
        MemoryContextSwitchTo(so->tempCtx);
 
-       entryIndexes = (int *) palloc(sizeof(int) * key->nentries);
+       entryIndexes = palloc_array(int, key->nentries);
        for (i = 0; i < key->nentries; i++)
            entryIndexes[i] = i;
        qsort_arg(entryIndexes, key->nentries, sizeof(int),
@@ -1873,7 +1873,7 @@ scanPendingInsert(IndexScanDesc scan, TIDBitmap *tbm, int64 *ntids)
    LockBuffer(pos.pendingBuffer, GIN_SHARE);
    pos.firstOffset = FirstOffsetNumber;
    UnlockReleaseBuffer(metabuffer);
-   pos.hasMatchKey = palloc(sizeof(bool) * so->nkeys);
+   pos.hasMatchKey = palloc_array(bool, so->nkeys);
 
    /*
     * loop for each heap row. scanGetCandidate returns full row or row's
index f87c60a230cbcbb745b01a976dd9d18270939762..df30dcc0228828b446769d70e9a200bfbc51eb87 100644 (file)
@@ -707,7 +707,7 @@ ginbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    {
        SortCoordinate coordinate;
 
-       coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+       coordinate = palloc0_object(SortCoordinateData);
        coordinate->isWorker = false;
        coordinate->nParticipants =
            state->bs_leader->nparticipanttuplesorts;
@@ -791,7 +791,7 @@ ginbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    /*
     * Return statistics
     */
-   result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+   result = palloc_object(IndexBuildResult);
 
    result->heap_tuples = reltuples;
    result->index_tuples = buildstate.indtuples;
@@ -867,7 +867,7 @@ gininsert(Relation index, Datum *values, bool *isnull,
    if (ginstate == NULL)
    {
        oldCtx = MemoryContextSwitchTo(indexInfo->ii_Context);
-       ginstate = (GinState *) palloc(sizeof(GinState));
+       ginstate = palloc_object(GinState);
        initGinState(ginstate, index);
        indexInfo->ii_AmCache = ginstate;
        MemoryContextSwitchTo(oldCtx);
@@ -934,7 +934,7 @@ _gin_begin_parallel(GinBuildState *buildstate, Relation heap, Relation index,
    Size        estsort;
    GinBuildShared *ginshared;
    Sharedsort *sharedsort;
-   GinLeader  *ginleader = (GinLeader *) palloc0(sizeof(GinLeader));
+   GinLeader  *ginleader = palloc0_object(GinLeader);
    WalUsage   *walusage;
    BufferUsage *bufferusage;
    bool        leaderparticipates = true;
@@ -1259,7 +1259,7 @@ AssertCheckGinBuffer(GinBuffer *buffer)
 static GinBuffer *
 GinBufferInit(Relation index)
 {
-   GinBuffer  *buffer = palloc0(sizeof(GinBuffer));
+   GinBuffer  *buffer = palloc0_object(GinBuffer);
    int         i,
                nKeys;
    TupleDesc   desc = RelationGetDescr(index);
@@ -1273,7 +1273,7 @@ GinBufferInit(Relation index)
 
    nKeys = IndexRelationGetNumberOfKeyAttributes(index);
 
-   buffer->ssup = palloc0(sizeof(SortSupportData) * nKeys);
+   buffer->ssup = palloc0_array(SortSupportData, nKeys);
 
    /*
     * Lookup ordering operator for the index key data type, and initialize
@@ -2030,7 +2030,7 @@ _gin_parallel_scan_and_build(GinBuildState *state,
    IndexInfo  *indexInfo;
 
    /* Initialize local tuplesort coordination state */
-   coordinate = palloc0(sizeof(SortCoordinateData));
+   coordinate = palloc0_object(SortCoordinateData);
    coordinate->isWorker = true;
    coordinate->nParticipants = -1;
    coordinate->sharedsort = sharedsort;
@@ -2279,7 +2279,7 @@ _gin_build_tuple(OffsetNumber attrnum, unsigned char category,
    while (ncompressed < nitems)
    {
        int         cnt;
-       GinSegmentInfo *seginfo = palloc(sizeof(GinSegmentInfo));
+       GinSegmentInfo *seginfo = palloc_object(GinSegmentInfo);
 
        seginfo->seg = ginCompressPostingList(&items[ncompressed],
                                              (nitems - ncompressed),
index 26081693383c7350e1ad75952efe8657802900e2..2ca635909f9cce6c8e2b01c6b144492fdcabe516 100644 (file)
@@ -33,7 +33,7 @@ ginbeginscan(Relation rel, int nkeys, int norderbys)
    scan = RelationGetIndexScan(rel, nkeys, norderbys);
 
    /* allocate private workspace */
-   so = (GinScanOpaque) palloc(sizeof(GinScanOpaqueData));
+   so = (GinScanOpaque) palloc_object(GinScanOpaqueData);
    so->keys = NULL;
    so->nkeys = 0;
    so->tempCtx = AllocSetContextCreate(CurrentMemoryContext,
@@ -98,7 +98,7 @@ ginFillScanEntry(GinScanOpaque so, OffsetNumber attnum,
    }
 
    /* Nope, create a new entry */
-   scanEntry = (GinScanEntry) palloc(sizeof(GinScanEntryData));
+   scanEntry = palloc_object(GinScanEntryData);
    scanEntry->queryKey = queryKey;
    scanEntry->queryCategory = queryCategory;
    scanEntry->isPartialMatch = isPartialMatch;
@@ -123,8 +123,7 @@ ginFillScanEntry(GinScanOpaque so, OffsetNumber attnum,
    if (so->totalentries >= so->allocentries)
    {
        so->allocentries *= 2;
-       so->entries = (GinScanEntry *)
-           repalloc(so->entries, so->allocentries * sizeof(GinScanEntry));
+       so->entries = repalloc_array(so->entries, GinScanEntry, so->allocentries);
    }
    so->entries[so->totalentries++] = scanEntry;
 
@@ -170,10 +169,8 @@ ginFillScanKey(GinScanOpaque so, OffsetNumber attnum,
    key->nuserentries = nQueryValues;
 
    /* Allocate one extra array slot for possible "hidden" entry */
-   key->scanEntry = (GinScanEntry *) palloc(sizeof(GinScanEntry) *
-                                            (nQueryValues + 1));
-   key->entryRes = (GinTernaryValue *) palloc0(sizeof(GinTernaryValue) *
-                                               (nQueryValues + 1));
+   key->scanEntry = palloc_array(GinScanEntry, nQueryValues + 1);
+   key->entryRes = palloc0_array(GinTernaryValue, nQueryValues + 1);
 
    key->query = query;
    key->queryValues = queryValues;
index 78f7b7a2495cf8ab9429ef4b6934080ce74c09dd..605f80aad39182dcc72d2b9728165d3242988ec2 100644 (file)
@@ -500,9 +500,9 @@ ginExtractEntries(GinState *ginstate, OffsetNumber attnum,
    if (isNull)
    {
        *nentries = 1;
-       entries = (Datum *) palloc(sizeof(Datum));
+       entries = palloc_object(Datum);
        entries[0] = (Datum) 0;
-       *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
+       *categories = palloc_object(GinNullCategory);
        (*categories)[0] = GIN_CAT_NULL_ITEM;
        return entries;
    }
@@ -522,9 +522,9 @@ ginExtractEntries(GinState *ginstate, OffsetNumber attnum,
    if (entries == NULL || *nentries <= 0)
    {
        *nentries = 1;
-       entries = (Datum *) palloc(sizeof(Datum));
+       entries = palloc_object(Datum);
        entries[0] = (Datum) 0;
-       *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
+       *categories = palloc_object(GinNullCategory);
        (*categories)[0] = GIN_CAT_EMPTY_ITEM;
        return entries;
    }
@@ -548,7 +548,7 @@ ginExtractEntries(GinState *ginstate, OffsetNumber attnum,
        keyEntryData *keydata;
        cmpEntriesArg arg;
 
-       keydata = (keyEntryData *) palloc(*nentries * sizeof(keyEntryData));
+       keydata = palloc_array(keyEntryData, *nentries);
        for (i = 0; i < *nentries; i++)
        {
            keydata[i].datum = entries[i];
index 2237efa50bbcff9a878577c1f8c9c9220f0226b4..d7baf7c847c4c914948bc13c8d1faa650927045f 100644 (file)
@@ -65,7 +65,7 @@ ginVacuumItemPointers(GinVacuumState *gvs, ItemPointerData *items,
                 * First TID to be deleted: allocate memory to hold the
                 * remaining items.
                 */
-               tmpitems = palloc(sizeof(ItemPointerData) * nitem);
+               tmpitems = palloc_array(ItemPointerData, nitem);
                memcpy(tmpitems, items, sizeof(ItemPointerData) * i);
            }
        }
@@ -260,7 +260,7 @@ ginScanToDelete(GinVacuumState *gvs, BlockNumber blkno, bool isRoot,
    {
        if (!parent->child)
        {
-           me = (DataPageDeleteStack *) palloc0(sizeof(DataPageDeleteStack));
+           me = palloc0_object(DataPageDeleteStack);
            me->parent = parent;
            parent->child = me;
            me->leftBuffer = InvalidBuffer;
@@ -584,7 +584,7 @@ ginbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
    if (stats == NULL)
    {
        /* Yes, so initialize stats to zeroes */
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
 
        /*
         * and cleanup any pending inserts
@@ -714,7 +714,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
     */
    if (stats == NULL)
    {
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
        initGinState(&ginstate, index);
        ginInsertCleanup(&ginstate, !AmAutoVacuumWorkerProcess(),
                         false, true, stats);
index 3fb1a1285c5ebcb9d6e09367012e9079ee9bf502..c26d8538f05395a030f5c9c7b901821924f48db9 100644 (file)
@@ -43,7 +43,7 @@ static void gistprunepage(Relation rel, Page page, Buffer buffer,
 
 
 #define ROTATEDIST(d) do { \
-   SplitPageLayout *tmp = (SplitPageLayout *) palloc0(sizeof(SplitPageLayout)); \
+   SplitPageLayout *tmp = palloc0_object(SplitPageLayout); \
    tmp->block.blkno = InvalidBlockNumber;  \
    tmp->buffer = InvalidBuffer;    \
    tmp->next = (d); \
@@ -392,7 +392,7 @@ gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
            /* Prepare a vector of all the downlinks */
            for (ptr = dist; ptr; ptr = ptr->next)
                ndownlinks++;
-           downlinks = palloc(sizeof(IndexTuple) * ndownlinks);
+           downlinks = palloc_array(IndexTuple, ndownlinks);
            for (i = 0, ptr = dist; ptr; ptr = ptr->next)
                downlinks[i++] = ptr->itup;
 
@@ -410,7 +410,7 @@ gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
            /* Prepare split-info to be returned to caller */
            for (ptr = dist; ptr; ptr = ptr->next)
            {
-               GISTPageSplitInfo *si = palloc(sizeof(GISTPageSplitInfo));
+               GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
 
                si->buf = ptr->buffer;
                si->downlink = ptr->itup;
@@ -823,7 +823,7 @@ gistdoinsert(Relation r, IndexTuple itup, Size freespace,
            xlocked = false;
 
            /* descend to the chosen child */
-           item = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+           item = palloc0_object(GISTInsertStack);
            item->blkno = childblkno;
            item->parent = stack;
            item->downlinkoffnum = downlinkoffnum;
@@ -923,7 +923,7 @@ gistFindPath(Relation r, BlockNumber child, OffsetNumber *downlinkoffnum)
               *ptr;
    BlockNumber blkno;
 
-   top = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+   top = palloc0_object(GISTInsertStack);
    top->blkno = GIST_ROOT_BLKNO;
    top->downlinkoffnum = InvalidOffsetNumber;
 
@@ -975,7 +975,7 @@ gistFindPath(Relation r, BlockNumber child, OffsetNumber *downlinkoffnum)
             * leaf pages, and we assume that there can't be any non-leaf
             * pages behind leaf pages.
             */
-           ptr = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+           ptr = palloc0_object(GISTInsertStack);
            ptr->blkno = GistPageGetOpaque(page)->rightlink;
            ptr->downlinkoffnum = InvalidOffsetNumber;
            ptr->parent = top->parent;
@@ -1000,7 +1000,7 @@ gistFindPath(Relation r, BlockNumber child, OffsetNumber *downlinkoffnum)
            else
            {
                /* Append this child to the list of pages to visit later */
-               ptr = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+               ptr = palloc0_object(GISTInsertStack);
                ptr->blkno = blkno;
                ptr->downlinkoffnum = i;
                ptr->parent = top;
@@ -1218,7 +1218,7 @@ gistfixsplit(GISTInsertState *state, GISTSTATE *giststate)
     */
    for (;;)
    {
-       GISTPageSplitInfo *si = palloc(sizeof(GISTPageSplitInfo));
+       GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
        IndexTuple  downlink;
 
        page = BufferGetPage(buf);
@@ -1482,8 +1482,8 @@ gistSplit(Relation r,
    gistSplitByKey(r, page, itup, len, giststate, &v, 0);
 
    /* form left and right vector */
-   lvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * (len + 1));
-   rvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * (len + 1));
+   lvectup = palloc_array(IndexTuple, len + 1);
+   rvectup = palloc_array(IndexTuple, len + 1);
 
    for (i = 0; i < v.splitVector.spl_nleft; i++)
        lvectup[i] = itup[v.splitVector.spl_left[i] - 1];
@@ -1552,7 +1552,7 @@ initGISTstate(Relation index)
    oldCxt = MemoryContextSwitchTo(scanCxt);
 
    /* Create and fill in the GISTSTATE */
-   giststate = (GISTSTATE *) palloc(sizeof(GISTSTATE));
+   giststate = palloc_object(GISTSTATE);
 
    giststate->scanCxt = scanCxt;
    giststate->tempCxt = scanCxt;   /* caller must change this if needed */
index be0fd5b753d7ec8ad066dfc518b5ea0bf8ad9dd8..b9fa196149dc1874018259936128b20dfcf502a7 100644 (file)
@@ -346,7 +346,7 @@ gistbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    /*
     * Return statistics
     */
-   result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+   result = palloc_object(IndexBuildResult);
 
    result->heap_tuples = reltuples;
    result->index_tuples = (double) buildstate.indtuples;
@@ -409,7 +409,7 @@ gist_indexsortbuild(GISTBuildState *state)
    state->bulkstate = smgr_bulk_start_rel(state->indexrel, MAIN_FORKNUM);
 
    /* Allocate a temporary buffer for the first leaf page batch. */
-   levelstate = palloc0(sizeof(GistSortedBuildLevelState));
+   levelstate = palloc0_object(GistSortedBuildLevelState);
    levelstate->pages[0] = palloc(BLCKSZ);
    levelstate->parent = NULL;
    gistinitpage(levelstate->pages[0], F_LEAF);
@@ -526,7 +526,7 @@ gist_indexsortbuild_levelstate_flush(GISTBuildState *state,
    else
    {
        /* Create split layout from single page */
-       dist = (SplitPageLayout *) palloc0(sizeof(SplitPageLayout));
+       dist = palloc0_object(SplitPageLayout);
        union_tuple = gistunion(state->indexrel, itvec, vect_len,
                                state->giststate);
        dist->itup = union_tuple;
@@ -597,7 +597,7 @@ gist_indexsortbuild_levelstate_flush(GISTBuildState *state,
        parent = levelstate->parent;
        if (parent == NULL)
        {
-           parent = palloc0(sizeof(GistSortedBuildLevelState));
+           parent = palloc0_object(GistSortedBuildLevelState);
            parent->pages[0] = palloc(BLCKSZ);
            parent->parent = NULL;
            gistinitpage(parent->pages[0], 0);
@@ -1154,7 +1154,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 
        /* Create an array of all the downlink tuples */
        ndownlinks = list_length(splitinfo);
-       downlinks = (IndexTuple *) palloc(sizeof(IndexTuple) * ndownlinks);
+       downlinks = palloc_array(IndexTuple, ndownlinks);
        i = 0;
        foreach(lc, splitinfo)
        {
index 0707254d18ea1f2c052cf7f3c7c3d3cd756a76ec..c86d17c4a562bb7eb5dcf94e24ad47b6e6a5ce20 100644 (file)
@@ -46,7 +46,7 @@ gistInitBuildBuffers(int pagesPerBuffer, int levelStep, int maxLevel)
    GISTBuildBuffers *gfbb;
    HASHCTL     hashCtl;
 
-   gfbb = palloc(sizeof(GISTBuildBuffers));
+   gfbb = palloc_object(GISTBuildBuffers);
    gfbb->pagesPerBuffer = pagesPerBuffer;
    gfbb->levelStep = levelStep;
 
@@ -60,7 +60,7 @@ gistInitBuildBuffers(int pagesPerBuffer, int levelStep, int maxLevel)
    /* Initialize free page management. */
    gfbb->nFreeBlocks = 0;
    gfbb->freeBlocksLen = 32;
-   gfbb->freeBlocks = (long *) palloc(gfbb->freeBlocksLen * sizeof(long));
+   gfbb->freeBlocks = palloc_array(long, gfbb->freeBlocksLen);
 
    /*
     * Current memory context will be used for all in-memory data structures
@@ -87,8 +87,7 @@ gistInitBuildBuffers(int pagesPerBuffer, int levelStep, int maxLevel)
     * buffers are inserted here when they are created.
     */
    gfbb->buffersOnLevelsLen = 1;
-   gfbb->buffersOnLevels = (List **) palloc(sizeof(List *) *
-                                            gfbb->buffersOnLevelsLen);
+   gfbb->buffersOnLevels = palloc_array(List *, gfbb->buffersOnLevelsLen);
    gfbb->buffersOnLevels[0] = NIL;
 
    /*
@@ -96,8 +95,7 @@ gistInitBuildBuffers(int pagesPerBuffer, int levelStep, int maxLevel)
     * into main memory.
     */
    gfbb->loadedBuffersLen = 32;
-   gfbb->loadedBuffers = (GISTNodeBuffer **) palloc(gfbb->loadedBuffersLen *
-                                                    sizeof(GISTNodeBuffer *));
+   gfbb->loadedBuffers = palloc_array(GISTNodeBuffer *, gfbb->loadedBuffersLen);
    gfbb->loadedBuffersCount = 0;
 
    gfbb->rootlevel = maxLevel;
@@ -582,9 +580,7 @@ gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb, GISTSTATE *giststate,
     * Allocate memory for information about relocation buffers.
     */
    splitPagesCount = list_length(splitinfo);
-   relocationBuffersInfos =
-       (RelocationBufferInfo *) palloc(sizeof(RelocationBufferInfo) *
-                                       splitPagesCount);
+   relocationBuffersInfos = palloc_array(RelocationBufferInfo, splitPagesCount);
 
    /*
     * Fill relocation buffers information for node buffers of pages produced
index f2ec6cbe2e5243407209a781102266123f19687f..9ac06504be17ed6adbca619579368816d5854b3e 100644 (file)
@@ -171,7 +171,7 @@ gist_box_union(PG_FUNCTION_ARGS)
               *pageunion;
 
    numranges = entryvec->n;
-   pageunion = (BOX *) palloc(sizeof(BOX));
+   pageunion = palloc_object(BOX);
    cur = DatumGetBoxP(entryvec->vector[0].key);
    memcpy(pageunion, cur, sizeof(BOX));
 
@@ -237,7 +237,7 @@ fallbackSplit(GistEntryVector *entryvec, GIST_SPLITVEC *v)
            v->spl_left[v->spl_nleft] = i;
            if (unionL == NULL)
            {
-               unionL = (BOX *) palloc(sizeof(BOX));
+               unionL = palloc_object(BOX);
                *unionL = *cur;
            }
            else
@@ -250,7 +250,7 @@ fallbackSplit(GistEntryVector *entryvec, GIST_SPLITVEC *v)
            v->spl_right[v->spl_nright] = i;
            if (unionR == NULL)
            {
-               unionR = (BOX *) palloc(sizeof(BOX));
+               unionR = palloc_object(BOX);
                *unionR = *cur;
            }
            else
@@ -698,8 +698,8 @@ gist_box_picksplit(PG_FUNCTION_ARGS)
    v->spl_nright = 0;
 
    /* Allocate bounding boxes of left and right groups */
-   leftBox = palloc0(sizeof(BOX));
-   rightBox = palloc0(sizeof(BOX));
+   leftBox = palloc0_object(BOX);
+   rightBox = palloc0_object(BOX);
 
    /*
     * Allocate an array for "common entries" - entries which can be placed to
@@ -1042,10 +1042,10 @@ gist_poly_compress(PG_FUNCTION_ARGS)
        POLYGON    *in = DatumGetPolygonP(entry->key);
        BOX        *r;
 
-       r = (BOX *) palloc(sizeof(BOX));
+       r = palloc_object(BOX);
        memcpy(r, &(in->boundbox), sizeof(BOX));
 
-       retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+       retval = palloc_object(GISTENTRY);
        gistentryinit(*retval, PointerGetDatum(r),
                      entry->rel, entry->page,
                      entry->offset, false);
@@ -1107,13 +1107,13 @@ gist_circle_compress(PG_FUNCTION_ARGS)
        CIRCLE     *in = DatumGetCircleP(entry->key);
        BOX        *r;
 
-       r = (BOX *) palloc(sizeof(BOX));
+       r = palloc_object(BOX);
        r->high.x = float8_pl(in->center.x, in->radius);
        r->low.x = float8_mi(in->center.x, in->radius);
        r->high.y = float8_pl(in->center.y, in->radius);
        r->low.y = float8_mi(in->center.y, in->radius);
 
-       retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+       retval = palloc_object(GISTENTRY);
        gistentryinit(*retval, PointerGetDatum(r),
                      entry->rel, entry->page,
                      entry->offset, false);
@@ -1171,9 +1171,9 @@ gist_point_compress(PG_FUNCTION_ARGS)
 
    if (entry->leafkey)         /* Point, actually */
    {
-       BOX        *box = palloc(sizeof(BOX));
+       BOX        *box = palloc_object(BOX);
        Point      *point = DatumGetPointP(entry->key);
-       GISTENTRY  *retval = palloc(sizeof(GISTENTRY));
+       GISTENTRY  *retval = palloc_object(GISTENTRY);
 
        box->high = box->low = *point;
 
@@ -1200,9 +1200,9 @@ gist_point_fetch(PG_FUNCTION_ARGS)
    Point      *r;
    GISTENTRY  *retval;
 
-   retval = palloc(sizeof(GISTENTRY));
+   retval = palloc_object(GISTENTRY);
 
-   r = (Point *) palloc(sizeof(Point));
+   r = palloc_object(Point);
    r->x = in->high.x;
    r->y = in->high.y;
    gistentryinit(*retval, PointerGetDatum(r),
index 700fa959d03d8ded5b9b57f1a65f7bcfe43ddf89..01b8ff0b6facf4b8c115ecbdad15738c7d090c3f 100644 (file)
@@ -90,7 +90,7 @@ gistbeginscan(Relation r, int nkeys, int norderbys)
    oldCxt = MemoryContextSwitchTo(giststate->scanCxt);
 
    /* initialize opaque data */
-   so = (GISTScanOpaque) palloc0(sizeof(GISTScanOpaqueData));
+   so = palloc0_object(GISTScanOpaqueData);
    so->giststate = giststate;
    giststate->tempCxt = createTempGistContext();
    so->queue = NULL;
@@ -101,8 +101,8 @@ gistbeginscan(Relation r, int nkeys, int norderbys)
    so->qual_ok = true;         /* in case there are zero keys */
    if (scan->numberOfOrderBys > 0)
    {
-       scan->xs_orderbyvals = palloc0(sizeof(Datum) * scan->numberOfOrderBys);
-       scan->xs_orderbynulls = palloc(sizeof(bool) * scan->numberOfOrderBys);
+       scan->xs_orderbyvals = palloc0_array(Datum, scan->numberOfOrderBys);
+       scan->xs_orderbynulls = palloc_array(bool, scan->numberOfOrderBys);
        memset(scan->xs_orderbynulls, true, sizeof(bool) * scan->numberOfOrderBys);
    }
 
index 49838ceb07b191ec6fdcfd14ce53e7727f878e39..21fea505d9c6d81083e13945aeebceaf9080cc8c 100644 (file)
@@ -51,7 +51,7 @@ gistunionsubkeyvec(GISTSTATE *giststate, IndexTuple *itvec,
    int         i,
                cleanedLen = 0;
 
-   cleanedItVec = (IndexTuple *) palloc(sizeof(IndexTuple) * gsvp->len);
+   cleanedItVec = palloc_array(IndexTuple, gsvp->len);
 
    for (i = 0; i < gsvp->len; i++)
    {
@@ -501,7 +501,7 @@ gistUserPicksplit(Relation r, GistEntryVector *entryvec, int attno, GistSplitVec
         * Locate don't-care tuples, if any.  If there are none, the split is
         * optimal, so just fall out and return false.
         */
-       v->spl_dontcare = (bool *) palloc0(sizeof(bool) * (entryvec->n + 1));
+       v->spl_dontcare = palloc0_array(bool, entryvec->n + 1);
 
        NumDontCare = findDontCares(r, giststate, entryvec->vector, v, attno);
 
@@ -738,9 +738,9 @@ gistSplitByKey(Relation r, Page page, IndexTuple *itup, int len,
                 * call will overwrite that with its own result.
                 */
                backupSplit = v->splitVector;
-               backupSplit.spl_left = (OffsetNumber *) palloc(sizeof(OffsetNumber) * len);
+               backupSplit.spl_left = palloc_array(OffsetNumber, len);
                memcpy(backupSplit.spl_left, v->splitVector.spl_left, sizeof(OffsetNumber) * v->splitVector.spl_nleft);
-               backupSplit.spl_right = (OffsetNumber *) palloc(sizeof(OffsetNumber) * len);
+               backupSplit.spl_right = palloc_array(OffsetNumber, len);
                memcpy(backupSplit.spl_right, v->splitVector.spl_right, sizeof(OffsetNumber) * v->splitVector.spl_nright);
 
                /* Recursively decide how to split the don't-care tuples */
index 0a29a6013efa545c552ce59294cd302012ed934d..6fc56c3c893f87dbaf6d5f46b27e752cdef98d4f 100644 (file)
@@ -100,7 +100,7 @@ gistextractpage(Page page, int *len /* out */ )
 
    maxoff = PageGetMaxOffsetNumber(page);
    *len = maxoff;
-   itvec = palloc(sizeof(IndexTuple) * maxoff);
+   itvec = palloc_array(IndexTuple, maxoff);
    for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
        itvec[i - FirstOffsetNumber] = (IndexTuple) PageGetItem(page, PageGetItemId(page, i));
 
@@ -113,7 +113,7 @@ gistextractpage(Page page, int *len /* out */ )
 IndexTuple *
 gistjoinvector(IndexTuple *itvec, int *len, IndexTuple *additvec, int addlen)
 {
-   itvec = (IndexTuple *) repalloc(itvec, sizeof(IndexTuple) * ((*len) + addlen));
+   itvec = repalloc_array(itvec, IndexTuple, (*len) + addlen);
    memmove(&itvec[*len], additvec, sizeof(IndexTuple) * addlen);
    *len += addlen;
    return itvec;
index b925eda2b9b42affee7d02906405ff1e49ab85e3..7591ad4da1acdb6608fa03453fbe71cbd4a524f6 100644 (file)
@@ -61,7 +61,7 @@ gistbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 {
    /* allocate stats if first time through, else re-use existing struct */
    if (stats == NULL)
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
 
    gistvacuumscan(info, stats, callback, callback_state);
 
@@ -85,7 +85,7 @@ gistvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
     */
    if (stats == NULL)
    {
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
        gistvacuumscan(info, stats, NULL, NULL);
    }
 
index 53061c819fbf0273dcd0fcada9cf0610e76238a5..e388252afdcc8402bff783c0ed366351764623e5 100644 (file)
@@ -193,7 +193,7 @@ hashbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    /*
     * Return statistics
     */
-   result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+   result = palloc_object(IndexBuildResult);
 
    result->heap_tuples = reltuples;
    result->index_tuples = buildstate.indtuples;
@@ -318,8 +318,7 @@ hashgettuple(IndexScanDesc scan, ScanDirection dir)
             * entries.
             */
            if (so->killedItems == NULL)
-               so->killedItems = (int *)
-                   palloc(MaxIndexTuplesPerPage * sizeof(int));
+               so->killedItems = palloc_array(int, MaxIndexTuplesPerPage);
 
            if (so->numKilled < MaxIndexTuplesPerPage)
                so->killedItems[so->numKilled++] = so->currPos.itemIndex;
@@ -381,7 +380,7 @@ hashbeginscan(Relation rel, int nkeys, int norderbys)
 
    scan = RelationGetIndexScan(rel, nkeys, norderbys);
 
-   so = (HashScanOpaque) palloc(sizeof(HashScanOpaqueData));
+   so = (HashScanOpaque) palloc_object(HashScanOpaqueData);
    HashScanPosInvalidate(so->currPos);
    so->hashso_bucket_buf = InvalidBuffer;
    so->hashso_split_bucket_buf = InvalidBuffer;
@@ -633,7 +632,7 @@ loop_top:
 
    /* return statistics */
    if (stats == NULL)
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
    stats->estimated_count = false;
    stats->num_index_tuples = num_index_tuples;
    stats->tuples_removed += tuples_removed;
index 92ae3cf53f52e8cd40e757ff676ce848f7d651d0..0fd41f4f4ca893d63021dbd2d041d43d8b7b6458 100644 (file)
@@ -59,7 +59,7 @@ struct HSpool
 HSpool *
 _h_spoolinit(Relation heap, Relation index, uint32 num_buckets)
 {
-   HSpool     *hspool = (HSpool *) palloc0(sizeof(HSpool));
+   HSpool     *hspool = palloc0_object(HSpool);
 
    hspool->index = index;
 
index 4d382a04338e665a3bb194a2791f54466277a03b..225f9829f229d9fd258bb0e9374536e65a1b7e36 100644 (file)
@@ -1133,7 +1133,7 @@ heap_beginscan(Relation relation, Snapshot snapshot,
     */
    if (flags & SO_TYPE_BITMAPSCAN)
    {
-       BitmapHeapScanDesc bscan = palloc(sizeof(BitmapHeapScanDescData));
+       BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
 
        /*
         * Bitmap Heap scans do not have any fields that a normal Heap Scan
@@ -1142,7 +1142,7 @@ heap_beginscan(Relation relation, Snapshot snapshot,
        scan = (HeapScanDesc) bscan;
    }
    else
-       scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
+       scan = (HeapScanDesc) palloc_object(HeapScanDescData);
 
    scan->rs_base.rs_rd = relation;
    scan->rs_base.rs_snapshot = snapshot;
@@ -1201,7 +1201,7 @@ heap_beginscan(Relation relation, Snapshot snapshot,
     * when doing a parallel scan.
     */
    if (parallel_scan != NULL)
-       scan->rs_parallelworkerdata = palloc(sizeof(ParallelBlockTableScanWorkerData));
+       scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
    else
        scan->rs_parallelworkerdata = NULL;
 
@@ -1210,7 +1210,7 @@ heap_beginscan(Relation relation, Snapshot snapshot,
     * initscan() and we don't want to allocate memory again
     */
    if (nkeys > 0)
-       scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
+       scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
    else
        scan->rs_base.rs_key = NULL;
 
@@ -2037,7 +2037,7 @@ GetBulkInsertState(void)
 {
    BulkInsertState bistate;
 
-   bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
+   bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
    bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
    bistate->current_buf = InvalidBuffer;
    bistate->next_free = InvalidBlockNumber;
@@ -6895,7 +6895,7 @@ FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
     * even member XIDs >= OldestXmin often won't be kept by second pass.
     */
    nnewmembers = 0;
-   newmembers = palloc(sizeof(MultiXactMember) * nmembers);
+   newmembers = palloc_array(MultiXactMember, nmembers);
    has_lockers = false;
    update_xid = InvalidTransactionId;
    update_committed = false;
@@ -8711,7 +8711,7 @@ bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
    Assert(delstate->ndeltids > 0);
 
    /* Calculate per-heap-block count of TIDs */
-   blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
+   blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
    for (int i = 0; i < delstate->ndeltids; i++)
    {
        TM_IndexDelete *ideltid = &delstate->deltids[i];
index bcbac844bb66962236c1a6bc8b7f11d11db37815..dd4fe6bf62ff4e70bdd301ddb3cb146114d5122a 100644 (file)
@@ -81,7 +81,7 @@ heapam_slot_callbacks(Relation relation)
 static IndexFetchTableData *
 heapam_index_fetch_begin(Relation rel)
 {
-   IndexFetchHeapData *hscan = palloc0(sizeof(IndexFetchHeapData));
+   IndexFetchHeapData *hscan = palloc0_object(IndexFetchHeapData);
 
    hscan->xs_base.rel = rel;
    hscan->xs_cbuf = InvalidBuffer;
@@ -717,8 +717,8 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
 
    /* Preallocate values/isnull arrays */
    natts = newTupDesc->natts;
-   values = (Datum *) palloc(natts * sizeof(Datum));
-   isnull = (bool *) palloc(natts * sizeof(bool));
+   values = palloc_array(Datum, natts);
+   isnull = palloc_array(bool, natts);
 
    /* Initialize the rewrite operation */
    rwstate = begin_heap_rewrite(OldHeap, NewHeap, OldestXmin, *xid_cutoff,
index 66ab48f0fe0d12f8e84fc768d9425a86892d0f83..7ce3c5e268546a05257ba8b024864b63d1a13650 100644 (file)
@@ -249,7 +249,7 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
    old_cxt = MemoryContextSwitchTo(rw_cxt);
 
    /* Create and fill in the state struct */
-   state = palloc0(sizeof(RewriteStateData));
+   state = palloc0_object(RewriteStateData);
 
    state->rs_old_rel = old_heap;
    state->rs_new_rel = new_heap;
index cc5b03eb7ceac09c4634b23f592ce3bdc08c61a4..eff7c39da7fe50317e7bc479a24b4f5af920c23e 100644 (file)
@@ -685,7 +685,7 @@ heap_vacuum_rel(Relation rel, const VacuumParams params,
     * of each rel.  It's convenient for code in lazy_scan_heap to always use
     * these temp copies.
     */
-   vacrel = (LVRelState *) palloc0(sizeof(LVRelState));
+   vacrel = palloc0_object(LVRelState);
    vacrel->dbname = get_database_name(MyDatabaseId);
    vacrel->relnamespace = get_namespace_name(RelationGetNamespace(rel));
    vacrel->relname = pstrdup(RelationGetRelationName(rel));
@@ -705,7 +705,7 @@ heap_vacuum_rel(Relation rel, const VacuumParams params,
    if (instrument && vacrel->nindexes > 0)
    {
        /* Copy index names used by instrumentation (not error reporting) */
-       indnames = palloc(sizeof(char *) * vacrel->nindexes);
+       indnames = palloc_array(char *, vacrel->nindexes);
        for (int i = 0; i < vacrel->nindexes; i++)
            indnames[i] = pstrdup(RelationGetRelationName(vacrel->indrels[i]));
    }
@@ -3582,7 +3582,7 @@ dead_items_alloc(LVRelState *vacrel, int nworkers)
     * locally.
     */
 
-   dead_items_info = (VacDeadItemsInfo *) palloc(sizeof(VacDeadItemsInfo));
+   dead_items_info = palloc_object(VacDeadItemsInfo);
    dead_items_info->max_bytes = vac_work_mem * (Size) 1024;
    dead_items_info->num_items = 0;
    vacrel->dead_items_info = dead_items_info;
index 4cf237019adafa595962d904828cee9b50ebf113..8d7e7171bd7e1ad58f0d6f333048f016075e4654 100644 (file)
@@ -118,7 +118,7 @@ identify_opfamily_groups(CatCList *oprlist, CatCList *proclist)
        }
 
        /* Time for a new group */
-       thisgroup = (OpFamilyOpFuncGroup *) palloc(sizeof(OpFamilyOpFuncGroup));
+       thisgroup = palloc_object(OpFamilyOpFuncGroup);
        if (oprform &&
            (!procform ||
             (oprform->amoplefttype < procform->amproclefttype ||
index c96917085c2742640e6f648f93e949facc1bc078..707c25289cd74aebcde4671145f38ee3de43c7c4 100644 (file)
@@ -81,7 +81,7 @@ RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
 {
    IndexScanDesc scan;
 
-   scan = (IndexScanDesc) palloc(sizeof(IndexScanDescData));
+   scan = palloc_object(IndexScanDescData);
 
    scan->heapRelation = NULL;  /* may be set later */
    scan->xs_heapfetch = NULL;
@@ -94,11 +94,11 @@ RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
     * We allocate key workspace here, but it won't get filled until amrescan.
     */
    if (nkeys > 0)
-       scan->keyData = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
+       scan->keyData = palloc_array(ScanKeyData, nkeys);
    else
        scan->keyData = NULL;
    if (norderbys > 0)
-       scan->orderByData = (ScanKey) palloc(sizeof(ScanKeyData) * norderbys);
+       scan->orderByData = palloc_array(ScanKeyData, norderbys);
    else
        scan->orderByData = NULL;
 
@@ -310,8 +310,8 @@ index_compute_xid_horizon_for_tuples(Relation irel,
    delstate.bottomup = false;
    delstate.bottomupfreespace = 0;
    delstate.ndeltids = 0;
-   delstate.deltids = palloc(nitems * sizeof(TM_IndexDelete));
-   delstate.status = palloc(nitems * sizeof(TM_IndexStatus));
+   delstate.deltids = palloc_array(TM_IndexDelete, nitems);
+   delstate.status = palloc_array(TM_IndexStatus, nitems);
 
    /* identify what the index tuples about to be deleted point to */
    for (int i = 0; i < nitems; i++)
@@ -401,7 +401,7 @@ systable_beginscan(Relation heapRelation,
    else
        irel = NULL;
 
-   sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
+   sysscan = palloc_object(SysScanDescData);
 
    sysscan->heap_rel = heapRelation;
    sysscan->irel = irel;
@@ -667,7 +667,7 @@ systable_beginscan_ordered(Relation heapRelation,
        elog(WARNING, "using index \"%s\" despite IgnoreSystemIndexes",
             RelationGetRelationName(indexRelation));
 
-   sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
+   sysscan = palloc_object(SysScanDescData);
 
    sysscan->heap_rel = heapRelation;
    sysscan->irel = indexRelation;
index a746de45dd377dc577cee43be9def5ec795e64f5..4c8ac8e753a83201a5b1bf6ee8c36758e92afcee 100644 (file)
@@ -82,7 +82,7 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz,
     * That ought to leave us with a good split point when pages full of
     * duplicates can be split several times.
     */
-   state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+   state = palloc_object(BTDedupStateData);
    state->deduplicate = true;
    state->nmaxitems = 0;
    state->maxpostingsize = Min(BTMaxItemSize / 2, INDEX_SIZE_MASK);
@@ -321,7 +321,7 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel,
    newitemsz += sizeof(ItemIdData);
 
    /* Initialize deduplication state */
-   state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+   state = palloc_object(BTDedupStateData);
    state->deduplicate = true;
    state->nmaxitems = 0;
    state->maxpostingsize = BLCKSZ; /* We're not really deduplicating */
@@ -355,8 +355,8 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel,
    delstate.bottomup = true;
    delstate.bottomupfreespace = Max(BLCKSZ / 16, newitemsz);
    delstate.ndeltids = 0;
-   delstate.deltids = palloc(MaxTIDsPerBTreePage * sizeof(TM_IndexDelete));
-   delstate.status = palloc(MaxTIDsPerBTreePage * sizeof(TM_IndexStatus));
+   delstate.deltids = palloc_array(TM_IndexDelete, MaxTIDsPerBTreePage);
+   delstate.status = palloc_array(TM_IndexStatus, MaxTIDsPerBTreePage);
 
    minoff = P_FIRSTDATAKEY(opaque);
    maxoff = PageGetMaxOffsetNumber(page);
index 3a4b791f2ab07b1d10ab8ad3d0ed65da6632f792..031eb76ba8cff0993d8a043a18ad65d38f35a409 100644 (file)
@@ -2963,7 +2963,7 @@ _bt_deadblocks(Page page, OffsetNumber *deletable, int ndeletable,
     */
    spacentids = ndeletable + 1;
    ntids = 0;
-   tidblocks = (BlockNumber *) palloc(sizeof(BlockNumber) * spacentids);
+   tidblocks = palloc_array(BlockNumber, spacentids);
 
    /*
     * First add the table block for the incoming newitem.  This is the one
index a8d56fe5a7caef34ef88fd0651681995e82e7203..cfb07b2bca93c3ebfe6425a24533d2a8ee9348d4 100644 (file)
@@ -2982,7 +2982,7 @@ _bt_pendingfsm_init(Relation rel, BTVacState *vstate, bool cleanuponly)
    vstate->maxbufsize = (int) maxbufsize;
 
    /* Allocate buffer, indicate that there are currently 0 pending pages */
-   vstate->pendingpages = palloc(sizeof(BTPendingFSM) * vstate->bufsize);
+   vstate->pendingpages = palloc_array(BTPendingFSM, vstate->bufsize);
    vstate->npendingpages = 0;
 }
 
index 211e20ebcbd5e6c36b922e215d69e7e72ef33143..6197b725fb1f5c4d821b9547a2be755846c6b037 100644 (file)
@@ -261,8 +261,7 @@ btgettuple(IndexScanDesc scan, ScanDirection dir)
                 * just forget any excess entries.
                 */
                if (so->killedItems == NULL)
-                   so->killedItems = (int *)
-                       palloc(MaxTIDsPerBTreePage * sizeof(int));
+                   so->killedItems = palloc_array(int, MaxTIDsPerBTreePage);
                if (so->numKilled < MaxTIDsPerBTreePage)
                    so->killedItems[so->numKilled++] = so->currPos.itemIndex;
            }
@@ -346,7 +345,7 @@ btbeginscan(Relation rel, int nkeys, int norderbys)
    scan = RelationGetIndexScan(rel, nkeys, norderbys);
 
    /* allocate private workspace */
-   so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));
+   so = palloc_object(BTScanOpaqueData);
    BTScanPosInvalidate(so->currPos);
    BTScanPosInvalidate(so->markPos);
    if (scan->numberOfKeys > 0)
@@ -1140,7 +1139,7 @@ btbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 
    /* allocate stats if first time through, else re-use existing struct */
    if (stats == NULL)
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
 
    /* Establish the vacuum cycle ID to use for this scan */
    /* The ENSURE stuff ensures we clean up shared memory on failure */
@@ -1201,7 +1200,7 @@ btvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
         * We handle the problem by making num_index_tuples an estimate in
         * cleanup-only case.
         */
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
        btvacuumscan(info, stats, NULL, NULL, 0);
        stats->estimated_count = true;
    }
index 7fcd7e94ea278dc9442f9431d622820033f9a0b1..aec71093661fbc5c9a83433765ef997e42674acd 100644 (file)
@@ -159,7 +159,7 @@ _bt_search(Relation rel, Relation heaprel, BTScanInsert key, Buffer *bufP,
         * page one level down, it usually ends up inserting a new pivot
         * tuple/downlink immediately after the location recorded here.
         */
-       new_stack = (BTStack) palloc(sizeof(BTStackData));
+       new_stack = (BTStack) palloc_object(BTStackData);
        new_stack->bts_blkno = BufferGetBlockNumber(*bufP);
        new_stack->bts_offset = offnum;
        new_stack->bts_parent = stack_in;
index 454adaee7dc15e989a6d2cc0e1a34e1ce44b3715..d7695dc1108f24098c62c29994c05d918a583daf 100644 (file)
@@ -335,7 +335,7 @@ btbuild(Relation heap, Relation index, IndexInfo *indexInfo)
    if (buildstate.btleader)
        _bt_end_parallel(buildstate.btleader);
 
-   result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+   result = palloc_object(IndexBuildResult);
 
    result->heap_tuples = reltuples;
    result->index_tuples = buildstate.indtuples;
@@ -366,7 +366,7 @@ static double
 _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate,
                    IndexInfo *indexInfo)
 {
-   BTSpool    *btspool = (BTSpool *) palloc0(sizeof(BTSpool));
+   BTSpool    *btspool = palloc0_object(BTSpool);
    SortCoordinate coordinate = NULL;
    double      reltuples = 0;
 
@@ -399,7 +399,7 @@ _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate,
     */
    if (buildstate->btleader)
    {
-       coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+       coordinate = palloc0_object(SortCoordinateData);
        coordinate->isWorker = false;
        coordinate->nParticipants =
            buildstate->btleader->nparticipanttuplesorts;
@@ -440,7 +440,7 @@ _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate,
     */
    if (indexInfo->ii_Unique)
    {
-       BTSpool    *btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
+       BTSpool    *btspool2 = palloc0_object(BTSpool);
        SortCoordinate coordinate2 = NULL;
 
        /* Initialize secondary spool */
@@ -457,7 +457,7 @@ _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate,
             * tuplesort_begin_index_btree() about the basic high level
             * coordination of a parallel sort.
             */
-           coordinate2 = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+           coordinate2 = palloc0_object(SortCoordinateData);
            coordinate2->isWorker = false;
            coordinate2->nParticipants =
                buildstate->btleader->nparticipanttuplesorts;
@@ -648,7 +648,7 @@ _bt_blwritepage(BTWriteState *wstate, BulkWriteBuffer buf, BlockNumber blkno)
 static BTPageState *
 _bt_pagestate(BTWriteState *wstate, uint32 level)
 {
-   BTPageState *state = (BTPageState *) palloc0(sizeof(BTPageState));
+   BTPageState *state = palloc0_object(BTPageState);
 
    /* create initial page for level */
    state->btps_buf = _bt_blnewpage(wstate, level);
@@ -1002,7 +1002,7 @@ _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup,
    if (last_off == P_HIKEY)
    {
        Assert(state->btps_lowkey == NULL);
-       state->btps_lowkey = palloc0(sizeof(IndexTupleData));
+       state->btps_lowkey = palloc0_object(IndexTupleData);
        state->btps_lowkey->t_info = sizeof(IndexTupleData);
        BTreeTupleSetNAtts(state->btps_lowkey, 0, false);
    }
@@ -1164,7 +1164,7 @@ _bt_load(BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
        itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
 
        /* Prepare SortSupport data for each column */
-       sortKeys = (SortSupport) palloc0(keysz * sizeof(SortSupportData));
+       sortKeys = palloc0_array(SortSupportData, keysz);
 
        for (i = 0; i < keysz; i++)
        {
@@ -1266,7 +1266,7 @@ _bt_load(BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
        /* merge is unnecessary, deduplicate into posting lists */
        BTDedupState dstate;
 
-       dstate = (BTDedupState) palloc(sizeof(BTDedupStateData));
+       dstate = palloc_object(BTDedupStateData);
        dstate->deduplicate = true; /* unused */
        dstate->nmaxitems = 0;  /* unused */
        dstate->maxpostingsize = 0; /* set later */
@@ -1404,7 +1404,7 @@ _bt_begin_parallel(BTBuildState *buildstate, bool isconcurrent, int request)
    Sharedsort *sharedsort;
    Sharedsort *sharedsort2;
    BTSpool    *btspool = buildstate->spool;
-   BTLeader   *btleader = (BTLeader *) palloc0(sizeof(BTLeader));
+   BTLeader   *btleader = palloc0_object(BTLeader);
    WalUsage   *walusage;
    BufferUsage *bufferusage;
    bool        leaderparticipates = true;
@@ -1693,7 +1693,7 @@ _bt_leader_participate_as_worker(BTBuildState *buildstate)
    int         sortmem;
 
    /* Allocate memory and initialize private spool */
-   leaderworker = (BTSpool *) palloc0(sizeof(BTSpool));
+   leaderworker = palloc0_object(BTSpool);
    leaderworker->heap = buildstate->spool->heap;
    leaderworker->index = buildstate->spool->index;
    leaderworker->isunique = buildstate->spool->isunique;
@@ -1705,7 +1705,7 @@ _bt_leader_participate_as_worker(BTBuildState *buildstate)
    else
    {
        /* Allocate memory for worker's own private secondary spool */
-       leaderworker2 = (BTSpool *) palloc0(sizeof(BTSpool));
+       leaderworker2 = palloc0_object(BTSpool);
 
        /* Initialize worker's own secondary spool */
        leaderworker2->heap = leaderworker->heap;
@@ -1796,7 +1796,7 @@ _bt_parallel_build_main(dsm_segment *seg, shm_toc *toc)
    indexRel = index_open(btshared->indexrelid, indexLockmode);
 
    /* Initialize worker's own spool */
-   btspool = (BTSpool *) palloc0(sizeof(BTSpool));
+   btspool = palloc0_object(BTSpool);
    btspool->heap = heapRel;
    btspool->index = indexRel;
    btspool->isunique = btshared->isunique;
@@ -1813,7 +1813,7 @@ _bt_parallel_build_main(dsm_segment *seg, shm_toc *toc)
    else
    {
        /* Allocate memory for worker's own private secondary spool */
-       btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
+       btspool2 = palloc0_object(BTSpool);
 
        /* Initialize worker's own secondary spool */
        btspool2->heap = btspool->heap;
@@ -1874,7 +1874,7 @@ _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2,
    IndexInfo  *indexInfo;
 
    /* Initialize local tuplesort coordination state */
-   coordinate = palloc0(sizeof(SortCoordinateData));
+   coordinate = palloc0_object(SortCoordinateData);
    coordinate->isWorker = true;
    coordinate->nParticipants = -1;
    coordinate->sharedsort = sharedsort;
@@ -1901,7 +1901,7 @@ _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2,
         * worker).  Worker processes are generally permitted to allocate
         * work_mem independently.
         */
-       coordinate2 = palloc0(sizeof(SortCoordinateData));
+       coordinate2 = palloc0_object(SortCoordinateData);
        coordinate2->isWorker = true;
        coordinate2->nParticipants = -1;
        coordinate2->sharedsort = sharedsort2;
index f0082f88c76959ee096937109c74ccfa5e83f0dc..651ab013025bbfdb6960c0c67361f75ab64d2fa0 100644 (file)
@@ -197,7 +197,7 @@ _bt_findsplitloc(Relation rel,
     * between tuples will be legal).
     */
    state.maxsplits = maxoff;
-   state.splits = palloc(sizeof(SplitPoint) * state.maxsplits);
+   state.splits = palloc_array(SplitPoint, state.maxsplits);
    state.nsplits = 0;
 
    /*
index d4a26de06a3d802ad9390247beaacb82e239b011..dbe67c166fdffcdb87f46ca8412484971844ba54 100644 (file)
@@ -469,7 +469,7 @@ btree_xlog_dedup(XLogReaderState *record)
        BTDedupInterval *intervals;
        Page        newpage;
 
-       state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+       state = palloc_object(BTDedupStateData);
        state->deduplicate = true;  /* unused */
        state->nmaxitems = 0;   /* unused */
        /* Conservatively use larger maxpostingsize than primary */
index 4eadb5187765fdd3ab800a1c325898ce82d9aa5f..1e1e61d20447ab065ce9a8c3f0415db867ffea31 100644 (file)
@@ -89,7 +89,7 @@ addNode(SpGistState *state, SpGistInnerTuple tuple, Datum label, int offset)
    else if (offset > tuple->nNodes)
        elog(ERROR, "invalid offset for adding node to SPGiST inner tuple");
 
-   nodes = palloc(sizeof(SpGistNodeTuple) * (tuple->nNodes + 1));
+   nodes = palloc_array(SpGistNodeTuple, tuple->nNodes + 1);
    SGITITERATE(tuple, i, node)
    {
        if (i < offset)
@@ -409,8 +409,8 @@ moveLeafs(Relation index, SpGistState *state,
 
    /* Locate the tuples to be moved, and count up the space needed */
    i = PageGetMaxOffsetNumber(current->page);
-   toDelete = (OffsetNumber *) palloc(sizeof(OffsetNumber) * i);
-   toInsert = (OffsetNumber *) palloc(sizeof(OffsetNumber) * (i + 1));
+   toDelete = palloc_array(OffsetNumber, i);
+   toInsert = palloc_array(OffsetNumber, i + 1);
 
    size = newLeafTuple->size + sizeof(ItemIdData);
 
@@ -634,7 +634,7 @@ checkAllTheSame(spgPickSplitIn *in, spgPickSplitOut *out, bool tooBig,
    {
        Datum       theLabel = out->nodeLabels[theNode];
 
-       out->nodeLabels = (Datum *) palloc(sizeof(Datum) * out->nNodes);
+       out->nodeLabels = palloc_array(Datum, out->nNodes);
        for (i = 0; i < out->nNodes; i++)
            out->nodeLabels[i] = theLabel;
    }
@@ -717,12 +717,12 @@ doPickSplit(Relation index, SpGistState *state,
     */
    max = PageGetMaxOffsetNumber(current->page);
    n = max + 1;
-   in.datums = (Datum *) palloc(sizeof(Datum) * n);
-   toDelete = (OffsetNumber *) palloc(sizeof(OffsetNumber) * n);
-   toInsert = (OffsetNumber *) palloc(sizeof(OffsetNumber) * n);
-   oldLeafs = (SpGistLeafTuple *) palloc(sizeof(SpGistLeafTuple) * n);
-   newLeafs = (SpGistLeafTuple *) palloc(sizeof(SpGistLeafTuple) * n);
-   leafPageSelect = (uint8 *) palloc(sizeof(uint8) * n);
+   in.datums = palloc_array(Datum, n);
+   toDelete = palloc_array(OffsetNumber, n);
+   toInsert = palloc_array(OffsetNumber, n);
+   oldLeafs = palloc_array(SpGistLeafTuple, n);
+   newLeafs = palloc_array(SpGistLeafTuple, n);
+   leafPageSelect = palloc_array(uint8, n);
 
    STORE_STATE(state, xlrec.stateSrc);
 
@@ -858,7 +858,7 @@ doPickSplit(Relation index, SpGistState *state,
        out.hasPrefix = false;
        out.nNodes = 1;
        out.nodeLabels = NULL;
-       out.mapTuplesToNodes = palloc0(sizeof(int) * in.nTuples);
+       out.mapTuplesToNodes = palloc0_array(int, in.nTuples);
 
        /*
         * Form new leaf tuples and count up the total space needed.
@@ -914,8 +914,8 @@ doPickSplit(Relation index, SpGistState *state,
     * out.nNodes with a value larger than the number of tuples on the input
     * page, we can't allocate these arrays before here.
     */
-   nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) * out.nNodes);
-   leafSizes = (int *) palloc0(sizeof(int) * out.nNodes);
+   nodes = palloc_array(SpGistNodeTuple, out.nNodes);
+   leafSizes = palloc0_array(int, out.nNodes);
 
    /*
     * Form nodes of inner tuple and inner tuple itself
@@ -1054,7 +1054,7 @@ doPickSplit(Relation index, SpGistState *state,
         * do so, even if totalLeafSizes is less than the available space,
         * because we can't split a group across pages.
         */
-       nodePageSelect = (uint8 *) palloc(sizeof(uint8) * out.nNodes);
+       nodePageSelect = palloc_array(uint8, out.nNodes);
 
        curspace = currentFreeSpace;
        newspace = PageGetExactFreeSpace(BufferGetPage(newLeafBuffer));
@@ -1740,8 +1740,7 @@ spgSplitNodeAction(Relation index, SpGistState *state,
     * Construct new prefix tuple with requested number of nodes.  We'll fill
     * in the childNodeN'th node's downlink below.
     */
-   nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) *
-                                      out->result.splitTuple.prefixNNodes);
+   nodes = palloc_array(SpGistNodeTuple, out->result.splitTuple.prefixNNodes);
 
    for (i = 0; i < out->result.splitTuple.prefixNNodes; i++)
    {
@@ -1769,7 +1768,7 @@ spgSplitNodeAction(Relation index, SpGistState *state,
     * same node datums, but with the prefix specified by the picksplit
     * function.
     */
-   nodes = palloc(sizeof(SpGistNodeTuple) * innerTuple->nNodes);
+   nodes = palloc_array(SpGistNodeTuple, innerTuple->nNodes);
    SGITITERATE(innerTuple, i, node)
    {
        nodes[i] = node;
index 6a61e093fa05a92c959d6824dddcb303c14bacdd..dda99755f666233f80b8e16c2acfb7c4de41bad7 100644 (file)
@@ -140,7 +140,7 @@ spgbuild(Relation heap, Relation index, IndexInfo *indexInfo)
                          true);
    }
 
-   result = (IndexBuildResult *) palloc0(sizeof(IndexBuildResult));
+   result = palloc0_object(IndexBuildResult);
    result->heap_tuples = reltuples;
    result->index_tuples = buildstate.indtuples;
 
index d6989759e5fd774316268ed8726c90fc3610be50..f0167d6ffa6889eeb5dad387620e709587d0fbdf 100644 (file)
@@ -114,7 +114,7 @@ spg_kd_picksplit(PG_FUNCTION_ARGS)
    SortedPoint *sorted;
    double      coord;
 
-   sorted = palloc(sizeof(*sorted) * in->nTuples);
+   sorted = palloc_array(SortedPoint, in->nTuples);
    for (i = 0; i < in->nTuples; i++)
    {
        sorted[i].p = DatumGetPointP(in->datums[i]);
@@ -132,8 +132,8 @@ spg_kd_picksplit(PG_FUNCTION_ARGS)
    out->nNodes = 2;
    out->nodeLabels = NULL;     /* we don't need node labels */
 
-   out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
-   out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+   out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+   out->leafTupleDatums = palloc_array(Datum, in->nTuples);
 
    /*
     * Note: points that have coordinates exactly equal to coord may get
@@ -259,7 +259,7 @@ spg_kd_inner_consistent(PG_FUNCTION_ARGS)
    if (!which)
        PG_RETURN_VOID();
 
-   out->nodeNumbers = (int *) palloc(sizeof(int) * 2);
+   out->nodeNumbers = palloc_array(int, 2);
 
    /*
     * When ordering scan keys are specified, we've to calculate distance for
@@ -273,8 +273,8 @@ spg_kd_inner_consistent(PG_FUNCTION_ARGS)
        BOX         infArea;
        BOX        *area;
 
-       out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
-       out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+       out->distances = palloc_array(double *, in->nNodes);
+       out->traversalValues = palloc_array(void *, in->nNodes);
 
        if (in->level == 0)
        {
@@ -335,7 +335,7 @@ spg_kd_inner_consistent(PG_FUNCTION_ARGS)
    }
 
    /* Set up level increments, too */
-   out->levelAdds = (int *) palloc(sizeof(int) * 2);
+   out->levelAdds = palloc_array(int, 2);
    out->levelAdds[0] = 1;
    out->levelAdds[1] = 1;
 
index 722c17ce2e5eca7adf3566820da611f3ccc5bdc2..e169c60a46340072d6ab301b160aa1af90118378 100644 (file)
@@ -64,7 +64,7 @@ spg_key_orderbys_distances(Datum key, bool isLeaf,
                           ScanKey orderbys, int norderbys)
 {
    int         sk_num;
-   double     *distances = (double *) palloc(norderbys * sizeof(double)),
+   double     *distances = palloc_array(double, norderbys),
               *distance = distances;
 
    for (sk_num = 0; sk_num < norderbys; ++sk_num, ++orderbys, ++distance)
@@ -81,7 +81,7 @@ spg_key_orderbys_distances(Datum key, bool isLeaf,
 BOX *
 box_copy(BOX *orig)
 {
-   BOX        *result = palloc(sizeof(BOX));
+   BOX        *result = palloc_object(BOX);
 
    *result = *orig;
    return result;
index 3e8cfa1709af31928e508a39dd31cea7410deb7a..75ffb09ca5aaa36f970ce7444dc9304f97886563 100644 (file)
@@ -82,7 +82,7 @@ getQuadrant(Point *centroid, Point *tst)
 static BOX *
 getQuadrantArea(BOX *bbox, Point *centroid, int quadrant)
 {
-   BOX        *result = (BOX *) palloc(sizeof(BOX));
+   BOX        *result = palloc_object(BOX);
 
    switch (quadrant)
    {
@@ -177,11 +177,11 @@ spg_quad_picksplit(PG_FUNCTION_ARGS)
    /* Use the median values of x and y as the centroid point */
    Point     **sorted;
 
-   sorted = palloc(sizeof(*sorted) * in->nTuples);
+   sorted = palloc_array(Point *, in->nTuples);
    for (i = 0; i < in->nTuples; i++)
        sorted[i] = DatumGetPointP(in->datums[i]);
 
-   centroid = palloc(sizeof(*centroid));
+   centroid = palloc_object(Point);
 
    qsort(sorted, in->nTuples, sizeof(*sorted), x_cmp);
    centroid->x = sorted[in->nTuples >> 1]->x;
@@ -189,7 +189,7 @@ spg_quad_picksplit(PG_FUNCTION_ARGS)
    centroid->y = sorted[in->nTuples >> 1]->y;
 #else
    /* Use the average values of x and y as the centroid point */
-   centroid = palloc0(sizeof(*centroid));
+   centroid = palloc0_object(Point);
 
    for (i = 0; i < in->nTuples; i++)
    {
@@ -207,8 +207,8 @@ spg_quad_picksplit(PG_FUNCTION_ARGS)
    out->nNodes = 4;
    out->nodeLabels = NULL;     /* we don't need node labels */
 
-   out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
-   out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+   out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+   out->leafTupleDatums = palloc_array(Datum, in->nTuples);
 
    for (i = 0; i < in->nTuples; i++)
    {
@@ -246,8 +246,8 @@ spg_quad_inner_consistent(PG_FUNCTION_ARGS)
     */
    if (in->norderbys > 0)
    {
-       out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
-       out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+       out->distances = palloc_array(double *, in->nNodes);
+       out->traversalValues = palloc_array(void *, in->nNodes);
 
        if (in->level == 0)
        {
@@ -270,7 +270,7 @@ spg_quad_inner_consistent(PG_FUNCTION_ARGS)
    {
        /* Report that all nodes should be visited */
        out->nNodes = in->nNodes;
-       out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+       out->nodeNumbers = palloc_array(int, in->nNodes);
        for (i = 0; i < in->nNodes; i++)
        {
            out->nodeNumbers[i] = i;
@@ -368,12 +368,12 @@ spg_quad_inner_consistent(PG_FUNCTION_ARGS)
            break;              /* no need to consider remaining conditions */
    }
 
-   out->levelAdds = palloc(sizeof(int) * 4);
+   out->levelAdds = palloc_array(int, 4);
    for (i = 0; i < 4; ++i)
        out->levelAdds[i] = 1;
 
    /* We must descend into the quadrant(s) identified by which */
-   out->nodeNumbers = (int *) palloc(sizeof(int) * 4);
+   out->nodeNumbers = palloc_array(int, 4);
    out->nNodes = 0;
 
    for (i = 1; i <= 4; i++)
index 25893050c5876527012e480cca1e18de8dec1649..946772f39576b0b1d5ac7d9369d439bed59f533f 100644 (file)
@@ -309,9 +309,9 @@ spgbeginscan(Relation rel, int keysz, int orderbysz)
 
    scan = RelationGetIndexScan(rel, keysz, orderbysz);
 
-   so = (SpGistScanOpaque) palloc0(sizeof(SpGistScanOpaqueData));
+   so = palloc0_object(SpGistScanOpaqueData);
    if (keysz > 0)
-       so->keyData = (ScanKey) palloc(sizeof(ScanKeyData) * keysz);
+       so->keyData = palloc_array(ScanKeyData, keysz);
    else
        so->keyData = NULL;
    initSpGistState(&so->state, scan->indexRelation);
@@ -336,16 +336,12 @@ spgbeginscan(Relation rel, int keysz, int orderbysz)
    if (scan->numberOfOrderBys > 0)
    {
        /* This will be filled in spgrescan, but allocate the space here */
-       so->orderByTypes = (Oid *)
-           palloc(sizeof(Oid) * scan->numberOfOrderBys);
-       so->nonNullOrderByOffsets = (int *)
-           palloc(sizeof(int) * scan->numberOfOrderBys);
+       so->orderByTypes = palloc_array(Oid, scan->numberOfOrderBys);
+       so->nonNullOrderByOffsets = palloc_array(int, scan->numberOfOrderBys);
 
        /* These arrays have constant contents, so we can fill them now */
-       so->zeroDistances = (double *)
-           palloc(sizeof(double) * scan->numberOfOrderBys);
-       so->infDistances = (double *)
-           palloc(sizeof(double) * scan->numberOfOrderBys);
+       so->zeroDistances = palloc_array(double, scan->numberOfOrderBys);
+       so->infDistances = palloc_array(double, scan->numberOfOrderBys);
 
        for (i = 0; i < scan->numberOfOrderBys; i++)
        {
@@ -353,10 +349,8 @@ spgbeginscan(Relation rel, int keysz, int orderbysz)
            so->infDistances[i] = get_float8_infinity();
        }
 
-       scan->xs_orderbyvals = (Datum *)
-           palloc0(sizeof(Datum) * scan->numberOfOrderBys);
-       scan->xs_orderbynulls = (bool *)
-           palloc(sizeof(bool) * scan->numberOfOrderBys);
+       scan->xs_orderbyvals = palloc0_array(Datum, scan->numberOfOrderBys);
+       scan->xs_orderbynulls = palloc_array(bool, scan->numberOfOrderBys);
        memset(scan->xs_orderbynulls, true,
               sizeof(bool) * scan->numberOfOrderBys);
    }
@@ -690,7 +684,7 @@ spgInnerTest(SpGistScanOpaque so, SpGistSearchItem *item,
    {
        /* force all children to be visited */
        out.nNodes = nNodes;
-       out.nodeNumbers = (int *) palloc(sizeof(int) * nNodes);
+       out.nodeNumbers = palloc_array(int, nNodes);
        for (i = 0; i < nNodes; i++)
            out.nodeNumbers[i] = i;
    }
@@ -703,7 +697,7 @@ spgInnerTest(SpGistScanOpaque so, SpGistSearchItem *item,
    {
        /* collect node pointers */
        SpGistNodeTuple node;
-       SpGistNodeTuple *nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) * nNodes);
+       SpGistNodeTuple *nodes = palloc_array(SpGistNodeTuple, nNodes);
 
        SGITITERATE(innerTuple, i, node)
        {
@@ -972,8 +966,8 @@ storeGettuple(SpGistScanOpaque so, ItemPointer heapPtr,
            so->distances[so->nPtrs] = NULL;
        else
        {
-           IndexOrderByDistance *distances =
-               palloc(sizeof(distances[0]) * so->numberOfOrderBys);
+           IndexOrderByDistance *distances = palloc_array(IndexOrderByDistance,
+                                                          so->numberOfOrderBys);
            int         i;
 
            for (i = 0; i < so->numberOfOrderBys; i++)
index 91f4ab260c2fe5d2b4b1e1ed6e6cb1778c9cca79..09be7ffe47eb696a618b5c075e2ccb17cc704303 100644 (file)
@@ -230,8 +230,7 @@ spg_text_choose(PG_FUNCTION_ARGS)
                    formTextDatum(prefixStr, commonLen);
            }
            out->result.splitTuple.prefixNNodes = 1;
-           out->result.splitTuple.prefixNodeLabels =
-               (Datum *) palloc(sizeof(Datum));
+           out->result.splitTuple.prefixNodeLabels = palloc_object(Datum);
            out->result.splitTuple.prefixNodeLabels[0] =
                Int16GetDatum(*(unsigned char *) (prefixStr + commonLen));
 
@@ -303,7 +302,7 @@ spg_text_choose(PG_FUNCTION_ARGS)
        out->result.splitTuple.prefixHasPrefix = in->hasPrefix;
        out->result.splitTuple.prefixPrefixDatum = in->prefixDatum;
        out->result.splitTuple.prefixNNodes = 1;
-       out->result.splitTuple.prefixNodeLabels = (Datum *) palloc(sizeof(Datum));
+       out->result.splitTuple.prefixNodeLabels = palloc_object(Datum);
        out->result.splitTuple.prefixNodeLabels[0] = Int16GetDatum(-2);
        out->result.splitTuple.childNodeN = 0;
        out->result.splitTuple.postfixHasPrefix = false;
@@ -371,7 +370,7 @@ spg_text_picksplit(PG_FUNCTION_ARGS)
    }
 
    /* Extract the node label (first non-common byte) from each value */
-   nodes = (spgNodePtr *) palloc(sizeof(spgNodePtr) * in->nTuples);
+   nodes = palloc_array(spgNodePtr, in->nTuples);
 
    for (i = 0; i < in->nTuples; i++)
    {
@@ -394,9 +393,9 @@ spg_text_picksplit(PG_FUNCTION_ARGS)
 
    /* And emit results */
    out->nNodes = 0;
-   out->nodeLabels = (Datum *) palloc(sizeof(Datum) * in->nTuples);
-   out->mapTuplesToNodes = (int *) palloc(sizeof(int) * in->nTuples);
-   out->leafTupleDatums = (Datum *) palloc(sizeof(Datum) * in->nTuples);
+   out->nodeLabels = palloc_array(Datum, in->nTuples);
+   out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+   out->leafTupleDatums = palloc_array(Datum, in->nTuples);
 
    for (i = 0; i < in->nTuples; i++)
    {
@@ -476,9 +475,9 @@ spg_text_inner_consistent(PG_FUNCTION_ARGS)
     * and see if it's consistent with the query.  If so, emit an entry into
     * the output arrays.
     */
-   out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
-   out->levelAdds = (int *) palloc(sizeof(int) * in->nNodes);
-   out->reconstructedValues = (Datum *) palloc(sizeof(Datum) * in->nNodes);
+   out->nodeNumbers = palloc_array(int, in->nNodes);
+   out->levelAdds = palloc_array(int, in->nNodes);
+   out->reconstructedValues = palloc_array(Datum, in->nNodes);
    out->nNodes = 0;
 
    for (i = 0; i < in->nNodes; i++)
index 87c31da71a52b11f83629a117930a99bbc9d47b2..a60ec85e8bedc6f7131605a515b3ef1eb507655d 100644 (file)
@@ -1177,7 +1177,7 @@ spgExtractNodeLabels(SpGistState *state, SpGistInnerTuple innerTuple)
    }
    else
    {
-       nodeLabels = (Datum *) palloc(sizeof(Datum) * innerTuple->nNodes);
+       nodeLabels = palloc_array(Datum, innerTuple->nNodes);
        SGITITERATE(innerTuple, i, node)
        {
            if (IndexTupleHasNulls(node))
index 71ef2e5036f219de968520dfd1bf090ca54a4493..cb5671c1a4e952e9d4514fcbd6ea65b14d76112c 100644 (file)
@@ -76,7 +76,7 @@ spgAddPendingTID(spgBulkDeleteState *bds, const ItemPointerData *tid)
        listLink = &pitem->next;
    }
    /* not there, so append new entry */
-   pitem = (spgVacPendingItem *) palloc(sizeof(spgVacPendingItem));
+   pitem = palloc_object(spgVacPendingItem);
    pitem->tid = *tid;
    pitem->done = false;
    pitem->next = NULL;
@@ -954,7 +954,7 @@ spgbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 
    /* allocate stats if first time through, else re-use existing struct */
    if (stats == NULL)
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
    bds.info = info;
    bds.stats = stats;
    bds.callback = callback;
@@ -994,7 +994,7 @@ spgvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
     */
    if (stats == NULL)
    {
-       stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+       stats = palloc0_object(IndexBulkDeleteResult);
        bds.info = info;
        bds.stats = stats;
        bds.callback = dummy_callback;
index b7110302b986726e0be88adf5ad1f9759d344b05..f635be0698fbba6bd1b4ac45f01bbf321f0edb4e 100644 (file)
@@ -901,7 +901,7 @@ spgRedoVacuumRedirect(XLogReaderState *record)
            int         max = PageGetMaxOffsetNumber(page);
            OffsetNumber *toDelete;
 
-           toDelete = palloc(sizeof(OffsetNumber) * max);
+           toDelete = palloc_array(OffsetNumber, max);
 
            for (i = xldata->firstPlaceholder; i <= max; i++)
                toDelete[i - xldata->firstPlaceholder] = i;
index 8db813b89fc643014855b3ff1eb718813c183352..c6740dbdd1b7576bcd16e09052de48df6f82c0fb 100644 (file)
@@ -129,7 +129,7 @@ system_samplescangetsamplesize(PlannerInfo *root,
 static void
 system_initsamplescan(SampleScanState *node, int eflags)
 {
-   node->tsm_state = palloc0(sizeof(SystemSamplerData));
+   node->tsm_state = palloc0_object(SystemSamplerData);
 }
 
 /*
index 72a4e50852a4b85642680a82618465297605b9bb..6ca3d44261ed1709885c7df0154448c48e698404 100644 (file)
@@ -419,8 +419,7 @@ MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
     * Note we have the same race condition here as above: j could be 0 at the
     * end of the loop.
     */
-   newMembers = (MultiXactMember *)
-       palloc(sizeof(MultiXactMember) * (nmembers + 1));
+   newMembers = palloc_array(MultiXactMember, nmembers + 1);
 
    for (i = 0, j = 0; i < nmembers; i++)
    {
index 94db1ec30126aca571143c4e6a7f96da3b06cb87..8428103eba41f6cc6b385bfed56d25fee0b9aa65 100644 (file)
@@ -186,7 +186,7 @@ CreateParallelContext(const char *library_name, const char *function_name,
    oldcontext = MemoryContextSwitchTo(TopTransactionContext);
 
    /* Initialize a new ParallelContext. */
-   pcxt = palloc0(sizeof(ParallelContext));
+   pcxt = palloc0_object(ParallelContext);
    pcxt->subid = GetCurrentSubTransactionId();
    pcxt->nworkers = nworkers;
    pcxt->nworkers_to_launch = nworkers;
@@ -453,7 +453,7 @@ InitializeParallelDSM(ParallelContext *pcxt)
                       clientconninfospace);
 
        /* Allocate space for worker information. */
-       pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
+       pcxt->worker = palloc0_array(ParallelWorkerInfo, pcxt->nworkers);
 
        /*
         * Establish error queues in dynamic shared memory.
@@ -648,8 +648,7 @@ LaunchParallelWorkers(ParallelContext *pcxt)
     */
    if (pcxt->nworkers_launched > 0)
    {
-       pcxt->known_attached_workers =
-           palloc0(sizeof(bool) * pcxt->nworkers_launched);
+       pcxt->known_attached_workers = palloc0_array(bool, pcxt->nworkers_launched);
        pcxt->nknown_attached_workers = 0;
    }
 
index ec3e323ec0c767f504aaaba666c082d60772032b..b8af25e82d1ac062090f347cd9ff096d6211addb 100644 (file)
@@ -87,7 +87,7 @@ readTimeLineHistory(TimeLineID targetTLI)
    /* Timeline 1 does not have a history file, so no need to check */
    if (targetTLI == 1)
    {
-       entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+       entry = palloc_object(TimeLineHistoryEntry);
        entry->tli = targetTLI;
        entry->begin = entry->end = InvalidXLogRecPtr;
        return list_make1(entry);
@@ -110,7 +110,7 @@ readTimeLineHistory(TimeLineID targetTLI)
                    (errcode_for_file_access(),
                     errmsg("could not open file \"%s\": %m", path)));
        /* Not there, so assume no parents */
-       entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+       entry = palloc_object(TimeLineHistoryEntry);
        entry->tli = targetTLI;
        entry->begin = entry->end = InvalidXLogRecPtr;
        return list_make1(entry);
@@ -175,7 +175,7 @@ readTimeLineHistory(TimeLineID targetTLI)
 
        lasttli = tli;
 
-       entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+       entry = palloc_object(TimeLineHistoryEntry);
        entry->tli = tli;
        entry->begin = prevend;
        entry->end = ((uint64) (switchpoint_hi)) << 32 | (uint64) switchpoint_lo;
@@ -198,7 +198,7 @@ readTimeLineHistory(TimeLineID targetTLI)
     * Create one more entry for the "tip" of the timeline, which has no entry
     * in the history file.
     */
-   entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+   entry = palloc_object(TimeLineHistoryEntry);
    entry->tli = targetTLI;
    entry->begin = prevend;
    entry->end = InvalidXLogRecPtr;
index da282b71b41a4a9d74cd9c08fe9046ba54e2edf7..ec4e3628bd550892ebc6a51558f08c04b9e51c0f 100644 (file)
@@ -684,7 +684,7 @@ GetPreparedTransactionList(GlobalTransaction *gxacts)
    }
 
    num = TwoPhaseState->numPrepXacts;
-   array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
+   array = palloc_array(GlobalTransactionData, num);
    *gxacts = array;
    for (i = 0; i < num; i++)
        memcpy(array + i, TwoPhaseState->prepXacts[i],
@@ -750,7 +750,7 @@ pg_prepared_xact(PG_FUNCTION_ARGS)
         * Collect all the 2PC status information that we will format and send
         * out as a result set.
         */
-       status = (Working_State *) palloc(sizeof(Working_State));
+       status = palloc_object(Working_State);
        funcctx->user_fctx = status;
 
        status->ngxacts = GetPreparedTransactionList(&status->array);
@@ -1027,7 +1027,7 @@ save_state_data(const void *data, uint32 len)
 
    if (padlen > records.bytes_free)
    {
-       records.tail->next = palloc0(sizeof(StateFileChunk));
+       records.tail->next = palloc0_object(StateFileChunk);
        records.tail = records.tail->next;
        records.tail->len = 0;
        records.tail->next = NULL;
@@ -1062,7 +1062,7 @@ StartPrepare(GlobalTransaction gxact)
    SharedInvalidationMessage *invalmsgs;
 
    /* Initialize linked list */
-   records.head = palloc0(sizeof(StateFileChunk));
+   records.head = palloc0_object(StateFileChunk);
    records.head->len = 0;
    records.head->next = NULL;
 
@@ -1453,7 +1453,7 @@ XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
    if (len != NULL)
        *len = XLogRecGetDataLen(xlogreader);
 
-   *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
+   *buf = palloc_array(char, XLogRecGetDataLen(xlogreader));
    memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
 
    XLogReaderFree(xlogreader);
index e48d4b7af6cd5ac28126d203d9c0aaf971b49e85..b69d452551ac1df787ea5c2e4c80bc0c324f95ba 100644 (file)
@@ -664,7 +664,7 @@ AssignTransactionId(TransactionState s)
        TransactionState *parents;
        size_t      parentOffset = 0;
 
-       parents = palloc(sizeof(TransactionState) * s->nestingLevel);
+       parents = palloc_array(TransactionState, s->nestingLevel);
        while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
        {
            parents[parentOffset++] = p;
index fb05e8e136db6a04edd4a1d49148ffad51b6c3f0..6a5640df51afc359c321be00cd021705dc908089 100644 (file)
@@ -4904,7 +4904,7 @@ void
 LocalProcessControlFile(bool reset)
 {
    Assert(reset || ControlFile == NULL);
-   ControlFile = palloc(sizeof(ControlFileData));
+   ControlFile = palloc_object(ControlFileData);
    ReadControlFile();
 }
 
@@ -9133,7 +9133,7 @@ do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces,
                continue;
            }
 
-           ti = palloc(sizeof(tablespaceinfo));
+           ti = palloc_object(tablespaceinfo);
            ti->oid = tsoid;
            ti->path = pstrdup(linkpath);
            ti->rpath = relpath;
index a50345f9bf761c552c5989e7477068092700a0bd..339cb75c3ad97dff2cb93dac05f1c7ad82e61c50 100644 (file)
@@ -90,7 +90,7 @@ pg_backup_start(PG_FUNCTION_ARGS)
    }
 
    oldcontext = MemoryContextSwitchTo(backupcontext);
-   backup_state = (BackupState *) palloc0(sizeof(BackupState));
+   backup_state = palloc0_object(BackupState);
    tablespace_map = makeStringInfo();
    MemoryContextSwitchTo(oldcontext);
 
index ed3aacabc986e0a2798188e3a60d9c5f1a5354a0..ccc29192c5a03e4b09b1e2fcf93fdbde3eac40a6 100644 (file)
@@ -364,7 +364,7 @@ XLogPrefetcherAllocate(XLogReaderState *reader)
    XLogPrefetcher *prefetcher;
    HASHCTL     ctl;
 
-   prefetcher = palloc0(sizeof(XLogPrefetcher));
+   prefetcher = palloc0_object(XLogPrefetcher);
    prefetcher->reader = reader;
 
    ctl.keysize = sizeof(RelFileLocator);
index 51dea342a4d14aed87ba2bd444e60c5375db697b..ae2398d6975b9b4b8a7d6266e10aba4063f3f128 100644 (file)
@@ -559,7 +559,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
     * Set the WAL reading processor now, as it will be needed when reading
     * the checkpoint record required (backup_label or not).
     */
-   private = palloc0(sizeof(XLogPageReadPrivate));
+   private = palloc0_object(XLogPageReadPrivate);
    xlogreader =
        XLogReaderAllocate(wal_segment_size, NULL,
                           XL_ROUTINE(.page_read = &XLogPageRead,
@@ -1416,7 +1416,7 @@ read_tablespace_map(List **tablespaces)
                         errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
            str[n++] = '\0';
 
-           ti = palloc0(sizeof(tablespaceinfo));
+           ti = palloc0_object(tablespaceinfo);
            errno = 0;
            ti->oid = strtoul(str, &endp, 10);
            if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
@@ -1467,7 +1467,7 @@ read_tablespace_map(List **tablespaces)
 EndOfWalRecoveryInfo *
 FinishWalRecovery(void)
 {
-   EndOfWalRecoveryInfo *result = palloc(sizeof(EndOfWalRecoveryInfo));
+   EndOfWalRecoveryInfo *result = palloc_object(EndOfWalRecoveryInfo);
    XLogRecPtr  lastRec;
    TimeLineID  lastRecTLI;
    XLogRecPtr  endOfLog;
index ce2a3e421462fd6e6a28c03b746ee94398cdaaeb..db55c0c5bd231c1f89db61230608b56cfb3756ee 100644 (file)
@@ -574,7 +574,7 @@ CreateFakeRelcacheEntry(RelFileLocator rlocator)
    Relation    rel;
 
    /* Allocate the Relation struct and all related space in one block. */
-   fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
+   fakeentry = palloc0_object(FakeRelCacheEntryData);
    rel = (Relation) fakeentry;
 
    rel->rd_rel = &fakeentry->pgc;
index 1fbc9af72baafd61eb49c989575d2e3682d8f759..719a758624deaa1a43f4729373fef06453955bd6 100644 (file)
@@ -262,7 +262,7 @@ perform_base_backup(basebackup_options *opt, bbsink *sink,
    total_checksum_failures = 0;
 
    /* Allocate backup related variables. */
-   backup_state = (BackupState *) palloc0(sizeof(BackupState));
+   backup_state = palloc0_object(BackupState);
    initStringInfo(&tablespace_map);
 
    basebackup_progress_wait_checkpoint();
@@ -289,7 +289,7 @@ perform_base_backup(basebackup_options *opt, bbsink *sink,
            PrepareForIncrementalBackup(ib, backup_state);
 
        /* Add a node for the base directory at the end */
-       newti = palloc0(sizeof(tablespaceinfo));
+       newti = palloc0_object(tablespaceinfo);
        newti->size = -1;
        state.tablespaces = lappend(state.tablespaces, newti);
 
@@ -1206,7 +1206,7 @@ sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
     * But we don't need it at all if this is not an incremental backup.
     */
    if (ib != NULL)
-       relative_block_numbers = palloc(sizeof(BlockNumber) * RELSEG_SIZE);
+       relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
 
    /*
     * Determine if the current path is a database directory that can contain
index eb45d3bcb663b2174c1c8f49f0858866b6604d03..8bb8d3939fe22bb9313caed038bf5a5a9a12108f 100644 (file)
@@ -107,7 +107,7 @@ static const bbsink_ops bbsink_copystream_ops = {
 bbsink *
 bbsink_copystream_new(bool send_to_client)
 {
-   bbsink_copystream *sink = palloc0(sizeof(bbsink_copystream));
+   bbsink_copystream *sink = palloc0_object(bbsink_copystream);
 
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_copystream_ops;
    sink->send_to_client = send_to_client;
index c4cbb5f5276443449dccb9a86fcc20aa4e65dbc5..aaad834291afccb19b4b12856596349a4b02158e 100644 (file)
@@ -76,7 +76,7 @@ bbsink_gzip_new(bbsink *next, pg_compress_specification *compress)
    Assert((compresslevel >= 1 && compresslevel <= 9) ||
           compresslevel == Z_DEFAULT_COMPRESSION);
 
-   sink = palloc0(sizeof(bbsink_gzip));
+   sink = palloc0_object(bbsink_gzip);
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_gzip_ops;
    sink->base.bbs_next = next;
    sink->compresslevel = compresslevel;
index 852ab57704516ee977e2b56e0ef3688137050537..7678e4f6ec33f39b98ca989e7bab1a589aaf83dc 100644 (file)
@@ -157,7 +157,7 @@ CreateIncrementalBackupInfo(MemoryContext mcxt)
 
    oldcontext = MemoryContextSwitchTo(mcxt);
 
-   ib = palloc0(sizeof(IncrementalBackupInfo));
+   ib = palloc0_object(IncrementalBackupInfo);
    ib->mcxt = mcxt;
    initStringInfo(&ib->buf);
 
@@ -169,7 +169,7 @@ CreateIncrementalBackupInfo(MemoryContext mcxt)
     */
    ib->manifest_files = backup_file_create(mcxt, 10000, NULL);
 
-   context = palloc0(sizeof(JsonManifestParseContext));
+   context = palloc0_object(JsonManifestParseContext);
    /* Parse the manifest. */
    context->private_data = ib;
    context->version_cb = manifest_process_version;
@@ -993,7 +993,7 @@ manifest_process_wal_range(JsonManifestParseContext *context,
                           XLogRecPtr end_lsn)
 {
    IncrementalBackupInfo *ib = context->private_data;
-   backup_wal_range *range = palloc(sizeof(backup_wal_range));
+   backup_wal_range *range = palloc_object(backup_wal_range);
 
    range->tli = tli;
    range->start_lsn = start_lsn;
index c5ceccb846f57c02db20d70f36021b18eef7223b..bd5704520fb7daea4df7a12f4f6a3108b62b3d20 100644 (file)
@@ -75,7 +75,7 @@ bbsink_lz4_new(bbsink *next, pg_compress_specification *compress)
    compresslevel = compress->level;
    Assert(compresslevel >= 0 && compresslevel <= 12);
 
-   sink = palloc0(sizeof(bbsink_lz4));
+   sink = palloc0_object(bbsink_lz4);
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_lz4_ops;
    sink->base.bbs_next = next;
    sink->compresslevel = compresslevel;
index dac205936229bbe930c3ade0aa3b684f03b96534..d783c9f57387502061acc3f9523ab463ae92c5e2 100644 (file)
@@ -62,7 +62,7 @@ bbsink_progress_new(bbsink *next, bool estimate_backup_size, bool incremental)
 
    Assert(next != NULL);
 
-   sink = palloc0(sizeof(bbsink));
+   sink = palloc0_object(bbsink);
    *((const bbsink_ops **) &sink->bbs_ops) = &bbsink_progress_ops;
    sink->bbs_next = next;
 
index 7678c6a231d98bacb48a8eebbfe9763d4d347c50..0d44a148f017cd27df793c6cf5e1a4ccfcdfc0d0 100644 (file)
@@ -59,7 +59,7 @@ static const bbsink_ops bbsink_server_ops = {
 bbsink *
 bbsink_server_new(bbsink *next, char *pathname)
 {
-   bbsink_server *sink = palloc0(sizeof(bbsink_server));
+   bbsink_server *sink = palloc0_object(bbsink_server);
 
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_server_ops;
    sink->pathname = pathname;
index 84b1309d3bdc83a501a1a0205dd0b41603c17e69..8b74828aed6d350295f06a4cccd035bd2adeee22 100644 (file)
@@ -96,7 +96,7 @@ BaseBackupAddTarget(char *name,
     * name into a newly-allocated chunk of memory.
     */
    oldcontext = MemoryContextSwitchTo(TopMemoryContext);
-   newtype = palloc(sizeof(BaseBackupTargetType));
+   newtype = palloc_object(BaseBackupTargetType);
    newtype->name = pstrdup(name);
    newtype->check_detail = check_detail;
    newtype->get_sink = get_sink;
@@ -132,7 +132,7 @@ BaseBackupGetTargetHandle(char *target, char *target_detail)
            BaseBackupTargetHandle *handle;
 
            /* Found the target. */
-           handle = palloc(sizeof(BaseBackupTargetHandle));
+           handle = palloc_object(BaseBackupTargetHandle);
            handle->type = ttype;
            handle->detail_arg = ttype->check_detail(target, target_detail);
 
index b2b743238f9d04353be76cc7b722012edd4a3a5b..95746c3ea4093741673e28de14b1783cae9d740f 100644 (file)
@@ -72,7 +72,7 @@ bbsink_throttle_new(bbsink *next, uint32 maxrate)
    Assert(next != NULL);
    Assert(maxrate > 0);
 
-   sink = palloc0(sizeof(bbsink_throttle));
+   sink = palloc0_object(bbsink_throttle);
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_throttle_ops;
    sink->base.bbs_next = next;
 
index 18b2e8fb0b3b664af42daeb503f546d8aca9ae4b..647ee0eb97831d42e1059b15f15c1ec1ca86a960 100644 (file)
@@ -70,7 +70,7 @@ bbsink_zstd_new(bbsink *next, pg_compress_specification *compress)
 
    Assert(next != NULL);
 
-   sink = palloc0(sizeof(bbsink_zstd));
+   sink = palloc0_object(bbsink_zstd);
    *((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_zstd_ops;
    sink->base.bbs_next = next;
    sink->compress = compress;
index 2689eae3328788cc06fda7417966d5bf480644e3..a843876337bf8ef1b7f52e5e5b2b2c3858e07e11 100644 (file)
@@ -73,7 +73,7 @@ GetWalSummaries(TimeLineID tli, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
            continue;
 
        /* Add it to the list. */
-       ws = palloc(sizeof(WalSummaryFile));
+       ws = palloc_object(WalSummaryFile);
        ws->tli = file_tli;
        ws->start_lsn = file_start_lsn;
        ws->end_lsn = file_end_lsn;
index fc8638c1b61b65e7c1a985e72ac2e419e439132a..4986b1ea7ed01f4e2c43ea05b3bbd9b70c5c3d9c 100644 (file)
@@ -742,7 +742,7 @@ populate_typ_list(void)
        Form_pg_type typForm = (Form_pg_type) GETSTRUCT(tup);
        struct typmap *newtyp;
 
-       newtyp = (struct typmap *) palloc(sizeof(struct typmap));
+       newtyp = palloc_object(struct typmap);
        Typ = lappend(Typ, newtyp);
 
        newtyp->am_oid = typForm->oid;
@@ -951,10 +951,10 @@ index_register(Oid heap,
 
    oldcxt = MemoryContextSwitchTo(nogc);
 
-   newind = (IndexList *) palloc(sizeof(IndexList));
+   newind = palloc_object(IndexList);
    newind->il_heap = heap;
    newind->il_ind = ind;
-   newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
+   newind->il_info = palloc_object(IndexInfo);
 
    memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
    /* expressions will likely be null, but may as well copy it */
index 8e70a85a3f73096bf35c5c0003747a0e14020894..838ed26d6b958a6957be51b9a8f476e60fedca39 100644 (file)
@@ -801,8 +801,7 @@ findDependentObjects(const ObjectAddress *object,
     * regression testing.)
     */
    maxDependentObjects = 128;  /* arbitrary initial allocation */
-   dependentObjects = (ObjectAddressAndFlags *)
-       palloc(maxDependentObjects * sizeof(ObjectAddressAndFlags));
+   dependentObjects = palloc_array(ObjectAddressAndFlags, maxDependentObjects);
    numDependentObjects = 0;
 
    ScanKeyInit(&key[0],
@@ -2616,12 +2615,11 @@ new_object_addresses(void)
 {
    ObjectAddresses *addrs;
 
-   addrs = palloc(sizeof(ObjectAddresses));
+   addrs = palloc_object(ObjectAddresses);
 
    addrs->numrefs = 0;
    addrs->maxrefs = 32;
-   addrs->refs = (ObjectAddress *)
-       palloc(addrs->maxrefs * sizeof(ObjectAddress));
+   addrs->refs = palloc_array(ObjectAddress, addrs->maxrefs);
    addrs->extras = NULL;       /* until/unless needed */
 
    return addrs;
index fd6537567ea27a3ac8e179822406e3a9b16fce20..265cc3e5fbf45c3cb8fe60f134ec71b0825db863 100644 (file)
@@ -732,7 +732,7 @@ InsertPgAttributeTuples(Relation pg_attribute_rel,
    /* Initialize the number of slots to use */
    nslots = Min(tupdesc->natts,
                 (MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_attribute)));
-   slot = palloc(sizeof(TupleTableSlot *) * nslots);
+   slot = palloc_array(TupleTableSlot *, nslots);
    for (int i = 0; i < nslots; i++)
        slot[i] = MakeSingleTupleTableSlot(td, &TTSOpsHeapTuple);
 
@@ -2459,7 +2459,7 @@ AddRelationNewConstraints(Relation rel,
 
        defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
 
-       cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+       cooked = palloc_object(CookedConstraint);
        cooked->contype = CONSTR_DEFAULT;
        cooked->conoid = defOid;
        cooked->name = NULL;
@@ -2593,7 +2593,7 @@ AddRelationNewConstraints(Relation rel,
 
            numchecks++;
 
-           cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+           cooked = palloc_object(CookedConstraint);
            cooked->contype = CONSTR_CHECK;
            cooked->conoid = constrOid;
            cooked->name = ccname;
@@ -2669,7 +2669,7 @@ AddRelationNewConstraints(Relation rel,
                                inhcount,
                                cdef->is_no_inherit);
 
-           nncooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+           nncooked = palloc_object(CookedConstraint);
            nncooked->contype = CONSTR_NOTNULL;
            nncooked->conoid = constrOid;
            nncooked->name = nnname;
index 5d9db167e5950b1d6212c46746c84cf59208e22c..8dea58ad96bf0b8e4f0888651bc2a1dca3094a78 100644 (file)
@@ -1414,7 +1414,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
    }
 
    /* Extract opclass options for each attribute */
-   opclassOptions = palloc0(sizeof(Datum) * newInfo->ii_NumIndexAttrs);
+   opclassOptions = palloc0_array(Datum, newInfo->ii_NumIndexAttrs);
    for (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)
        opclassOptions[i] = get_attoptions(oldIndexId, i + 1);
 
@@ -2678,9 +2678,9 @@ BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
     */
    Assert(ii->ii_Unique);
 
-   ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
-   ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
-   ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
+   ii->ii_UniqueOps = palloc_array(Oid, indnkeyatts);
+   ii->ii_UniqueProcs = palloc_array(Oid, indnkeyatts);
+   ii->ii_UniqueStrats = palloc_array(uint16, indnkeyatts);
 
    /*
     * We have to look up the operator's strategy number.  This provides a
index d23474da4fb27ebe0c8fe207fdc20df1e5986326..c94089caa582075cbc3220025d15206c41f43f90 100644 (file)
@@ -3929,7 +3929,7 @@ GetSearchPathMatcher(MemoryContext context)
 
    oldcxt = MemoryContextSwitchTo(context);
 
-   result = (SearchPathMatcher *) palloc0(sizeof(SearchPathMatcher));
+   result = palloc0_object(SearchPathMatcher);
    schemas = list_copy(activeSearchPath);
    while (schemas && linitial_oid(schemas) != activeCreationNamespace)
    {
@@ -3960,7 +3960,7 @@ CopySearchPathMatcher(SearchPathMatcher *path)
 {
    SearchPathMatcher *result;
 
-   result = (SearchPathMatcher *) palloc(sizeof(SearchPathMatcher));
+   result = palloc_object(SearchPathMatcher);
    result->schemas = list_copy(path->schemas);
    result->addCatalog = path->addCatalog;
    result->addTemp = path->addTemp;
index c75b7131ed703ae1acd6a70225161baa62e10bfe..fa6c6df598ae82d1a98e998867ee1245e9702b32 100644 (file)
@@ -6144,8 +6144,8 @@ strlist_to_textarray(List *list)
                                   ALLOCSET_DEFAULT_SIZES);
    oldcxt = MemoryContextSwitchTo(memcxt);
 
-   datums = (Datum *) palloc(sizeof(Datum) * list_length(list));
-   nulls = palloc(sizeof(bool) * list_length(list));
+   datums = palloc_array(Datum, list_length(list));
+   nulls = palloc_array(bool, list_length(list));
 
    foreach(cell, list)
    {
index 5b2a813230627f94d53d82b0ca949d9e44664957..43b4507d86e038a49448b8df64257e2c88b4be95 100644 (file)
@@ -846,7 +846,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
        {
            CookedConstraint *cooked;
 
-           cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+           cooked = palloc_object(CookedConstraint);
 
            cooked->contype = CONSTR_NOTNULL;
            cooked->conoid = conForm->oid;
index c8b11f887e2743b57b4887c24ac8a21d976a9977..a6f63e107bb69f0e125f2a2e4a1ad879a2bfa714 100644 (file)
@@ -88,7 +88,7 @@ recordMultipleDependencies(const ObjectAddress *depender,
     */
    max_slots = Min(nreferenced,
                    MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_depend));
-   slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+   slot = palloc_array(TupleTableSlot *, max_slots);
 
    /* Don't open indexes unless we need to make an update */
    indstate = NULL;
index da9c2a46cfaa14354ea87b24ea979424007ba22f..07998839affdca9b39e0d54a789312a01ece2ecf 100644 (file)
@@ -120,7 +120,7 @@ EnumValuesCreate(Oid enumTypeOid, List *vals)
     * allocating the next), trouble could only occur if the OID counter wraps
     * all the way around before we finish. Which seems unlikely.
     */
-   oids = (Oid *) palloc(num_elems * sizeof(Oid));
+   oids = palloc_array(Oid, num_elems);
 
    for (elemno = 0; elemno < num_elems; elemno++)
    {
@@ -148,7 +148,7 @@ EnumValuesCreate(Oid enumTypeOid, List *vals)
    /* allocate the slots to use and initialize them */
    nslots = Min(num_elems,
                 MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_enum));
-   slot = palloc(sizeof(TupleTableSlot *) * nslots);
+   slot = palloc_array(TupleTableSlot *, nslots);
    for (int i = 0; i < nslots; i++)
        slot[i] = MakeSingleTupleTableSlot(RelationGetDescr(pg_enum),
                                           &TTSOpsHeapTuple);
@@ -375,7 +375,7 @@ restart:
    nelems = list->n_members;
 
    /* Sort the existing members by enumsortorder */
-   existing = (HeapTuple *) palloc(nelems * sizeof(HeapTuple));
+   existing = palloc_array(HeapTuple, nelems);
    for (i = 0; i < nelems; i++)
        existing[i] = &(list->members[i]->tuple);
 
index 0994220c53d5b5671ba3d8b47d60299d3a51a11a..be5ef5e4c0e07be770505d49e1d86e9f993754fc 100644 (file)
@@ -1086,7 +1086,7 @@ GetPublication(Oid pubid)
 
    pubform = (Form_pg_publication) GETSTRUCT(tup);
 
-   pub = (Publication *) palloc(sizeof(Publication));
+   pub = palloc_object(Publication);
    pub->oid = pubid;
    pub->name = pstrdup(NameStr(pubform->pubname));
    pub->alltables = pubform->puballtables;
@@ -1196,7 +1196,7 @@ pg_get_publication_tables(PG_FUNCTION_ARGS)
             */
            foreach(lc, pub_elem_tables)
            {
-               published_rel *table_info = (published_rel *) palloc(sizeof(published_rel));
+               published_rel *table_info = palloc_object(published_rel);
 
                table_info->relid = lfirst_oid(lc);
                table_info->pubid = pub_elem->oid;
@@ -1299,7 +1299,7 @@ pg_get_publication_tables(PG_FUNCTION_ARGS)
            TupleDesc   desc = RelationGetDescr(rel);
            int         i;
 
-           attnums = (int16 *) palloc(desc->natts * sizeof(int16));
+           attnums = palloc_array(int16, desc->natts);
 
            for (i = 0; i < desc->natts; i++)
            {
index 16e3e5c7457db8d8f3dbc4eee17c1ff740bf0a15..fe4e453667621db3d6a71de83582f6a3cb4054e7 100644 (file)
@@ -791,7 +791,7 @@ checkSharedDependencies(Oid classId, Oid objectId,
            }
            if (!stored)
            {
-               dep = (remoteDep *) palloc(sizeof(remoteDep));
+               dep = palloc_object(remoteDep);
                dep->dbOid = sdepForm->dbid;
                dep->count = 1;
                remDeps = lappend(remDeps, dep);
@@ -913,7 +913,7 @@ copyTemplateDependencies(Oid templateDbId, Oid newDbId)
     * know that they will be used.
     */
    max_slots = MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_shdepend);
-   slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+   slot = palloc_array(TupleTableSlot *, max_slots);
 
    indstate = CatalogOpenIndexes(sdepRel);
 
index 180e77e94845b1bae99c01bd4b891c65853a461e..ad6fbd77ffdd38d65f6540518866c7f362a44bf5 100644 (file)
@@ -89,7 +89,7 @@ GetSubscription(Oid subid, bool missing_ok)
 
    subform = (Form_pg_subscription) GETSTRUCT(tup);
 
-   sub = (Subscription *) palloc(sizeof(Subscription));
+   sub = palloc_object(Subscription);
    sub->oid = subid;
    sub->dbid = subform->subdbid;
    sub->skiplsn = subform->subskiplsn;
@@ -618,7 +618,7 @@ GetSubscriptionRelations(Oid subid, bool tables, bool sequences,
             relkind == RELKIND_PARTITIONED_TABLE) && !tables)
            continue;
 
-       relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
+       relstate = palloc_object(SubscriptionRelState);
        relstate->relid = subrel->srrelid;
        relstate->state = subrel->srsubstate;
        d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
index c58e9418ac3132ded6645874134127f3ba903737..d06c1c68174ef66c0c833db53417afb93652881f 100644 (file)
@@ -707,12 +707,12 @@ smgrDoPendingDeletes(bool isCommit)
                if (maxrels == 0)
                {
                    maxrels = 8;
-                   srels = palloc(sizeof(SMgrRelation) * maxrels);
+                   srels = palloc_array(SMgrRelation, maxrels);
                }
                else if (maxrels <= nrels)
                {
                    maxrels *= 2;
-                   srels = repalloc(srels, sizeof(SMgrRelation) * maxrels);
+                   srels = repalloc_array(srels, SMgrRelation, maxrels);
                }
 
                srels[nrels++] = srel;
@@ -829,12 +829,12 @@ smgrDoPendingSyncs(bool isCommit, bool isParallelWorker)
            if (maxrels == 0)
            {
                maxrels = 8;
-               srels = palloc(sizeof(SMgrRelation) * maxrels);
+               srels = palloc_array(SMgrRelation, maxrels);
            }
            else if (maxrels <= nrels)
            {
                maxrels *= 2;
-               srels = repalloc(srels, sizeof(SMgrRelation) * maxrels);
+               srels = repalloc_array(srels, SMgrRelation, maxrels);
            }
 
            srels[nrels++] = srel;
@@ -909,7 +909,7 @@ smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
        *ptr = NULL;
        return 0;
    }
-   rptr = (RelFileLocator *) palloc(nrels * sizeof(RelFileLocator));
+   rptr = palloc_array(RelFileLocator, nrels);
    *ptr = rptr;
    for (pending = pendingDeletes; pending != NULL; pending = pending->next)
    {
index b2429170679a871ee811ea063d7c563c544a7d64..5e2a7a8234ec83fada724ed252eb2fcdf964f1bf 100644 (file)
@@ -1079,7 +1079,7 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
    /*
     * Create the VacAttrStats struct.
     */
-   stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
+   stats = palloc0_object(VacAttrStats);
    stats->attstattarget = attstattarget;
 
    /*
@@ -1910,7 +1910,7 @@ std_typanalyze(VacAttrStats *stats)
                             NULL);
 
    /* Save the operator info for compute_stats routines */
-   mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
+   mystats = palloc_object(StdAnalyzeData);
    mystats->eqopr = eqopr;
    mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
    mystats->ltopr = ltopr;
@@ -2865,7 +2865,7 @@ compute_scalar_stats(VacAttrStatsP stats,
 
            /* Must copy the target values into anl_context */
            old_context = MemoryContextSwitchTo(stats->anl_context);
-           corrs = (float4 *) palloc(sizeof(float4));
+           corrs = palloc_object(float4);
            MemoryContextSwitchTo(old_context);
 
            /*----------
index d1e772efb722b214aa0777a7957866bb51df9c8f..2120c85ccb4cb21e75cd803be09bd2f2138e3e40 100644 (file)
@@ -1672,7 +1672,7 @@ get_tables_to_cluster(MemoryContext cluster_context)
        /* Use a permanent memory context for the result list */
        old_context = MemoryContextSwitchTo(cluster_context);
 
-       rtc = (RelToCluster *) palloc(sizeof(RelToCluster));
+       rtc = palloc_object(RelToCluster);
        rtc->tableOid = index->indrelid;
        rtc->indexOid = index->indexrelid;
        rtcs = lappend(rtcs, rtc);
@@ -1726,7 +1726,7 @@ get_tables_to_cluster_partitioned(MemoryContext cluster_context, Oid indexOid)
        /* Use a permanent memory context for the result list */
        old_context = MemoryContextSwitchTo(cluster_context);
 
-       rtc = (RelToCluster *) palloc(sizeof(RelToCluster));
+       rtc = palloc_object(RelToCluster);
        rtc->tableOid = relid;
        rtc->indexOid = indexrelid;
        rtcs = lappend(rtcs, rtc);
index 28e878c3688702892d92c6cb0de3dbf1fcb7fc61..6454a39a01f0cd682a5a82842153b2a776bf5203 100644 (file)
@@ -561,7 +561,7 @@ ProcessCopyOptions(ParseState *pstate,
 
    /* Support external use for option sanity checking */
    if (opts_out == NULL)
-       opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
+       opts_out = palloc0_object(CopyFormatOptions);
 
    opts_out->file_encoding = -1;
 
index 12781963b4f95bcdf7800f72a725705ea7e223c8..2ae3d2ba86e766718f8ddc29ee3fc27affd3e9f9 100644 (file)
@@ -364,7 +364,7 @@ CopyMultiInsertBufferInit(ResultRelInfo *rri)
 {
    CopyMultiInsertBuffer *buffer;
 
-   buffer = (CopyMultiInsertBuffer *) palloc(sizeof(CopyMultiInsertBuffer));
+   buffer = palloc_object(CopyMultiInsertBuffer);
    memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
    buffer->resultRelInfo = rri;
    buffer->bistate = (rri->ri_FdwRoutine == NULL) ? GetBulkInsertState() : NULL;
@@ -1558,7 +1558,7 @@ BeginCopyFrom(ParseState *pstate,
    };
 
    /* Allocate workspace and zero all fields */
-   cstate = (CopyFromStateData *) palloc0(sizeof(CopyFromStateData));
+   cstate = palloc0_object(CopyFromStateData);
 
    /*
     * We allocate everything used by a cstate in a new memory context. This
index cef452584e5835a9a9dbbaf28ab4ab781325cb02..dae91630ac3ea60872539ba66b800d186beb862e 100644 (file)
@@ -720,7 +720,7 @@ BeginCopyTo(ParseState *pstate,
 
 
    /* Allocate workspace and zero all fields */
-   cstate = (CopyToStateData *) palloc0(sizeof(CopyToStateData));
+   cstate = palloc0_object(CopyToStateData);
 
    /*
     * We allocate everything used by a cstate in a new memory context. This
@@ -1527,7 +1527,7 @@ copy_dest_destroy(DestReceiver *self)
 DestReceiver *
 CreateCopyDestReceiver(void)
 {
-   DR_copy    *self = (DR_copy *) palloc(sizeof(DR_copy));
+   DR_copy    *self = palloc_object(DR_copy);
 
    self->pub.receiveSlot = copy_dest_receive;
    self->pub.rStartup = copy_dest_startup;
index 1ccc2e55c6434583cc7eac3bfdcc1babfc7d38a3..ddc45e3aa0d3fe350e7e465ec5b0f5a86cb9d6bf 100644 (file)
@@ -439,7 +439,7 @@ CreateTableAsRelExists(CreateTableAsStmt *ctas)
 DestReceiver *
 CreateIntoRelDestReceiver(IntoClause *intoClause)
 {
-   DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
+   DR_intorel *self = palloc0_object(DR_intorel);
 
    self->pub.receiveSlot = intorel_receive;
    self->pub.rStartup = intorel_startup;
index da85cd2d43527ebc7171b7a7cd3742b506b00b58..d1f3be89b35f005f7906d5de6febddbe9ba76132 100644 (file)
@@ -431,7 +431,7 @@ ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid,
             classForm->oid);
 
    /* Prepare a rel info element and add it to the list. */
-   relinfo = (CreateDBRelInfo *) palloc(sizeof(CreateDBRelInfo));
+   relinfo = palloc_object(CreateDBRelInfo);
    if (OidIsValid(classForm->reltablespace))
        relinfo->rlocator.spcOid = classForm->reltablespace;
    else
index f34868da5ab9406d1188b496aa34a113c7f7cdef..e718230813018c62adf73233ac36184049f27e70 100644 (file)
@@ -364,7 +364,7 @@ filter_list_to_array(List *filterlist)
    int         i = 0,
                l = list_length(filterlist);
 
-   data = (Datum *) palloc(l * sizeof(Datum));
+   data = palloc_array(Datum, l);
 
    foreach(lc, filterlist)
    {
@@ -1286,7 +1286,7 @@ EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool no
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   obj = palloc0(sizeof(SQLDropObject));
+   obj = palloc0_object(SQLDropObject);
    obj->address = *object;
    obj->original = original;
    obj->normal = normal;
@@ -1726,7 +1726,7 @@ EventTriggerCollectSimpleCommand(ObjectAddress address,
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc(sizeof(CollectedCommand));
+   command = palloc_object(CollectedCommand);
 
    command->type = SCT_Simple;
    command->in_extension = creating_extension;
@@ -1762,7 +1762,7 @@ EventTriggerAlterTableStart(Node *parsetree)
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc(sizeof(CollectedCommand));
+   command = palloc_object(CollectedCommand);
 
    command->type = SCT_AlterTable;
    command->in_extension = creating_extension;
@@ -1818,7 +1818,7 @@ EventTriggerCollectAlterTableSubcmd(Node *subcmd, ObjectAddress address)
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   newsub = palloc(sizeof(CollectedATSubcmd));
+   newsub = palloc_object(CollectedATSubcmd);
    newsub->address = address;
    newsub->parsetree = copyObject(subcmd);
 
@@ -1892,7 +1892,7 @@ EventTriggerCollectGrant(InternalGrant *istmt)
    /*
     * This is tedious, but necessary.
     */
-   icopy = palloc(sizeof(InternalGrant));
+   icopy = palloc_object(InternalGrant);
    memcpy(icopy, istmt, sizeof(InternalGrant));
    icopy->objects = list_copy(istmt->objects);
    icopy->grantees = list_copy(istmt->grantees);
@@ -1901,7 +1901,7 @@ EventTriggerCollectGrant(InternalGrant *istmt)
        icopy->col_privs = lappend(icopy->col_privs, copyObject(lfirst(cell)));
 
    /* Now collect it, using the copied InternalGrant */
-   command = palloc(sizeof(CollectedCommand));
+   command = palloc_object(CollectedCommand);
    command->type = SCT_Grant;
    command->in_extension = creating_extension;
    command->d.grant.istmt = icopy;
@@ -1932,7 +1932,7 @@ EventTriggerCollectAlterOpFam(AlterOpFamilyStmt *stmt, Oid opfamoid,
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc(sizeof(CollectedCommand));
+   command = palloc_object(CollectedCommand);
    command->type = SCT_AlterOpFamily;
    command->in_extension = creating_extension;
    ObjectAddressSet(command->d.opfam.address,
@@ -1965,7 +1965,7 @@ EventTriggerCollectCreateOpClass(CreateOpClassStmt *stmt, Oid opcoid,
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc0(sizeof(CollectedCommand));
+   command = palloc0_object(CollectedCommand);
    command->type = SCT_CreateOpClass;
    command->in_extension = creating_extension;
    ObjectAddressSet(command->d.createopc.address,
@@ -1999,12 +1999,12 @@ EventTriggerCollectAlterTSConfig(AlterTSConfigurationStmt *stmt, Oid cfgId,
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc0(sizeof(CollectedCommand));
+   command = palloc0_object(CollectedCommand);
    command->type = SCT_AlterTSConfig;
    command->in_extension = creating_extension;
    ObjectAddressSet(command->d.atscfg.address,
                     TSConfigRelationId, cfgId);
-   command->d.atscfg.dictIds = palloc(sizeof(Oid) * ndicts);
+   command->d.atscfg.dictIds = palloc_array(Oid, ndicts);
    memcpy(command->d.atscfg.dictIds, dictIds, sizeof(Oid) * ndicts);
    command->d.atscfg.ndicts = ndicts;
    command->parsetree = (Node *) copyObject(stmt);
@@ -2033,7 +2033,7 @@ EventTriggerCollectAlterDefPrivs(AlterDefaultPrivilegesStmt *stmt)
 
    oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
 
-   command = palloc0(sizeof(CollectedCommand));
+   command = palloc0_object(CollectedCommand);
    command->type = SCT_AlterDefaultPrivileges;
    command->d.defprivs.objtype = stmt->action->objtype;
    command->in_extension = creating_extension;
index 7e699f8595e03d39115284a163361284d7f870f4..5a6390631eba91cce340417d86bfc45a995312ab 100644 (file)
@@ -4980,7 +4980,7 @@ ExplainCreateWorkersState(int num_workers)
 {
    ExplainWorkersState *wstate;
 
-   wstate = (ExplainWorkersState *) palloc(sizeof(ExplainWorkersState));
+   wstate = palloc_object(ExplainWorkersState);
    wstate->num_workers = num_workers;
    wstate->worker_inited = (bool *) palloc0(num_workers * sizeof(bool));
    wstate->worker_str = (StringInfoData *)
index 95685d7e88dd96eec5b27a2e6dd77f41f4bfba7c..5833aa80fb5b2ab4577b87af42c04db92b93b3f4 100644 (file)
@@ -276,7 +276,7 @@ CreateExplainSerializeDestReceiver(ExplainState *es)
 {
    SerializeDestReceiver *self;
 
-   self = (SerializeDestReceiver *) palloc0(sizeof(SerializeDestReceiver));
+   self = palloc0_object(SerializeDestReceiver);
 
    self->pub.receiveSlot = serializeAnalyzeReceive;
    self->pub.rStartup = serializeAnalyzeStartup;
index dae256809d27f6683c6f7a46f0be54f5f233bf47..a6623f8fa5295f9ec114ecff9a9ff93f63ac48af 100644 (file)
@@ -60,7 +60,7 @@ static int    ExplainExtensionOptionsAllocated = 0;
 ExplainState *
 NewExplainState(void)
 {
-   ExplainState *es = (ExplainState *) palloc0(sizeof(ExplainState));
+   ExplainState *es = palloc0_object(ExplainState);
 
    /* Set default options (most fields can be left as zeroes). */
    es->costs = true;
@@ -294,10 +294,7 @@ SetExplainExtensionState(ExplainState *es, int extension_id, void *opaque)
        int         i;
 
        i = pg_nextpower2_32(extension_id + 1);
-       es->extension_state = (void **)
-           repalloc0(es->extension_state,
-                     es->extension_state_allocated * sizeof(void *),
-                     i * sizeof(void *));
+       es->extension_state = repalloc0_array(es->extension_state, void *, es->extension_state_allocated, i);
        es->extension_state_allocated = i;
    }
 
index ebc204c446213a5e7ef55037094accbc51d288f1..c43b74e319e809983caadee9eb40048b709aca58 100644 (file)
@@ -724,7 +724,7 @@ read_extension_aux_control_file(const ExtensionControlFile *pcontrol,
    /*
     * Flat-copy the struct.  Pointer fields share values with original.
     */
-   acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
+   acontrol = palloc_object(ExtensionControlFile);
    memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
 
    /*
@@ -1349,7 +1349,7 @@ get_ext_ver_info(const char *versionname, List **evi_list)
            return evi;
    }
 
-   evi = (ExtensionVersionInfo *) palloc(sizeof(ExtensionVersionInfo));
+   evi = palloc_object(ExtensionVersionInfo);
    evi->name = pstrdup(versionname);
    evi->reachable = NIL;
    evi->installable = false;
index 59d00638ee61459d6244707de8a435fe9d54929a..8a435cd93dbf7345d54cfe85991c268104d4c9d6 100644 (file)
@@ -913,7 +913,7 @@ interpret_AS_clause(Oid languageOid, const char *languageName,
    {
        SQLFunctionParseInfoPtr pinfo;
 
-       pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
+       pinfo = palloc0_object(SQLFunctionParseInfo);
 
        pinfo->fname = funcname;
        pinfo->nargs = list_length(parameterTypes);
index a5c579ce112730d18547e57f18b3a62e5436f154..a1fd4cab35b68f388e939f1ae59e16f2cc9d9a2d 100644 (file)
@@ -463,7 +463,7 @@ refresh_matview_datafill(DestReceiver *dest, Query *query,
 DestReceiver *
 CreateTransientRelDestReceiver(Oid transientoid)
 {
-   DR_transientrel *self = (DR_transientrel *) palloc0(sizeof(DR_transientrel));
+   DR_transientrel *self = palloc0_object(DR_transientrel);
 
    self->pub.receiveSlot = transientrel_receive;
    self->pub.rStartup = transientrel_startup;
@@ -713,7 +713,7 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
     * include all rows.
     */
    tupdesc = matviewRel->rd_att;
-   opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
+   opUsedForQual = palloc0_array(Oid, relnatts);
    foundUniqueIndex = false;
 
    indexoidlist = RelationGetIndexList(matviewRel);
index a6dd8eab5186b876dcec89c6e6fa22166757ee57..992ae789b00620f54eba6411b0ac712ebc982664 100644 (file)
@@ -523,7 +523,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
 #endif
 
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = false;
                member->object = operOid;
                member->number = item->number;
@@ -547,7 +547,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
                                   get_func_name(funcOid));
 #endif
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = true;
                member->object = funcOid;
                member->number = item->number;
@@ -940,7 +940,7 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
 #endif
 
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = false;
                member->object = operOid;
                member->number = item->number;
@@ -970,7 +970,7 @@ AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
 #endif
 
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = true;
                member->object = funcOid;
                member->number = item->number;
@@ -1058,7 +1058,7 @@ AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
                                    item->number, maxOpNumber)));
                processTypesSpec(item->class_args, &lefttype, &righttype);
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = false;
                member->number = item->number;
                member->lefttype = lefttype;
@@ -1074,7 +1074,7 @@ AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
                                    item->number, maxProcNumber)));
                processTypesSpec(item->class_args, &lefttype, &righttype);
                /* Save the info */
-               member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+               member = palloc0_object(OpFamilyMember);
                member->is_func = true;
                member->number = item->number;
                member->lefttype = lefttype;
index 83056960fe47ede0e1da7a125cd06e4b4a96e45c..5bd5f8c9968f7ca37e6610d944f312878585f287 100644 (file)
@@ -144,7 +144,7 @@ policy_role_list_to_array(List *roles, int *num_roles)
    if (roles == NIL)
    {
        *num_roles = 1;
-       role_oids = (Datum *) palloc(*num_roles * sizeof(Datum));
+       role_oids = palloc_array(Datum, *num_roles);
        role_oids[0] = ObjectIdGetDatum(ACL_ID_PUBLIC);
 
        return role_oids;
@@ -471,7 +471,7 @@ RemoveRoleFromObjectPolicy(Oid roleid, Oid classid, Oid policy_id)
     * Ordinarily there'd be exactly one, but we must cope with duplicate
     * mentions, since CREATE/ALTER POLICY historically have allowed that.
     */
-   role_oids = (Datum *) palloc(num_roles * sizeof(Datum));
+   role_oids = palloc_array(Datum, num_roles);
    for (i = 0, j = 0; i < num_roles; i++)
    {
        if (roles[i] != roleid)
@@ -945,7 +945,7 @@ AlterPolicy(AlterPolicyStmt *stmt)
 
        nitems = ARR_DIMS(policy_roles)[0];
 
-       role_oids = (Datum *) palloc(nitems * sizeof(Datum));
+       role_oids = palloc_array(Datum, nitems);
 
        for (i = 0; i < nitems; i++)
            role_oids[i] = ObjectIdGetDatum(roles[i]);
index 1faf3a8c372836c5b845563058d389600eff03be..a198350895051053039cf2e820a72a3836624bb2 100644 (file)
@@ -1345,7 +1345,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup,
             */
            if (!found)
            {
-               oldrel = palloc(sizeof(PublicationRelInfo));
+               oldrel = palloc_object(PublicationRelInfo);
                oldrel->whereClause = NULL;
                oldrel->columns = NIL;
                oldrel->relation = table_open(oldrelid,
@@ -1757,7 +1757,7 @@ OpenTableList(List *tables)
            continue;
        }
 
-       pub_rel = palloc(sizeof(PublicationRelInfo));
+       pub_rel = palloc_object(PublicationRelInfo);
        pub_rel->relation = rel;
        pub_rel->whereClause = t->whereClause;
        pub_rel->columns = t->columns;
@@ -1826,7 +1826,7 @@ OpenTableList(List *tables)
 
                /* find_all_inheritors already got lock */
                rel = table_open(childrelid, NoLock);
-               pub_rel = palloc(sizeof(PublicationRelInfo));
+               pub_rel = palloc_object(PublicationRelInfo);
                pub_rel->relation = rel;
                /* child inherits WHERE clause from parent */
                pub_rel->whereClause = t->whereClause;
index cee5d7bbb9c7eba3ea0cb16ec1eba2f74543438f..07bed6e1487eb5270dfed970804c399cdaea6574 100644 (file)
@@ -573,7 +573,7 @@ register_label_provider(const char *provider_name, check_object_relabel_type hoo
    MemoryContext oldcxt;
 
    oldcxt = MemoryContextSwitchTo(TopMemoryContext);
-   provider = palloc(sizeof(LabelProvider));
+   provider = palloc_object(LabelProvider);
    provider->provider_name = pstrdup(provider_name);
    provider->hook = hook;
    label_provider_list = lappend(label_provider_list, provider);
index 8c856af3493bdfc29d14ae2f7c87ca82661c46d8..abbcaff0838b941c42cdf0b8ac883388efefaee2 100644 (file)
@@ -566,7 +566,7 @@ publicationListToArray(List *publist)
                                   ALLOCSET_DEFAULT_SIZES);
    oldcxt = MemoryContextSwitchTo(memcxt);
 
-   datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
+   datums = palloc_array(Datum, list_length(publist));
 
    check_duplicates_in_publist(publist, datums);
 
@@ -1055,7 +1055,7 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data,
            {
                char        state;
                XLogRecPtr  statelsn;
-               SubRemoveRels *remove_rel = palloc(sizeof(SubRemoveRels));
+               SubRemoveRels *remove_rel = palloc_object(SubRemoveRels);
 
                /*
                 * Lock pg_subscription_rel with AccessExclusiveLock to
index 07e5b95782e45aa8e786666366554c5c40275ec2..1c9ef53be205e0364a246fdff6d79d34f4123459 100644 (file)
@@ -999,7 +999,7 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 
            Assert(colDef->cooked_default == NULL);
 
-           rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+           rawEnt = palloc_object(RawColumnDefault);
            rawEnt->attnum = attnum;
            rawEnt->raw_default = colDef->raw_default;
            rawEnt->generated = colDef->generated;
@@ -1009,7 +1009,7 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
        {
            CookedConstraint *cooked;
 
-           cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+           cooked = palloc_object(CookedConstraint);
            cooked->contype = CONSTR_DEFAULT;
            cooked->conoid = InvalidOid;    /* until created */
            cooked->name = NULL;
@@ -6568,7 +6568,7 @@ ATGetQueueEntry(List **wqueue, Relation rel)
     * Not there, so add it.  Note that we make a copy of the relation's
     * existing descriptor before anything interesting can happen to it.
     */
-   tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
+   tab = palloc0_object(AlteredTableInfo);
    tab->relid = relid;
    tab->rel = NULL;            /* set later */
    tab->relkind = rel->rd_rel->relkind;
@@ -7406,7 +7406,7 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
    {
        RawColumnDefault *rawEnt;
 
-       rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+       rawEnt = palloc_object(RawColumnDefault);
        rawEnt->attnum = attribute->attnum;
        rawEnt->raw_default = copyObject(colDef->raw_default);
        rawEnt->generated = colDef->generated;
@@ -7507,7 +7507,7 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
            defval = expression_planner(defval);
 
            /* Add the new default to the newvals list */
-           newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+           newval = palloc0_object(NewColumnValue);
            newval->attnum = attribute->attnum;
            newval->expr = defval;
            newval->is_generated = (colDef->generated != '\0');
@@ -8176,7 +8176,7 @@ ATExecColumnDefault(Relation rel, const char *colName,
        /* SET DEFAULT */
        RawColumnDefault *rawEnt;
 
-       rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+       rawEnt = palloc_object(RawColumnDefault);
        rawEnt->attnum = attnum;
        rawEnt->raw_default = newDefault;
        rawEnt->generated = '\0';
@@ -8704,7 +8704,7 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
                      false, false);
 
    /* Prepare to store the new expression, in the catalogs */
-   rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+   rawEnt = palloc_object(RawColumnDefault);
    rawEnt->attnum = attnum;
    rawEnt->raw_default = newExpr;
    rawEnt->generated = attgenerated;
@@ -8721,7 +8721,7 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
        /* Prepare for table rewrite */
        defval = (Expr *) build_column_default(rel, attnum);
 
-       newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+       newval = palloc0_object(NewColumnValue);
        newval->attnum = attnum;
        newval->expr = expression_planner(defval);
        newval->is_generated = true;
@@ -9949,7 +9949,7 @@ ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
        {
            NewConstraint *newcon;
 
-           newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+           newcon = palloc0_object(NewConstraint);
            newcon->name = ccon->name;
            newcon->contype = ccon->contype;
            newcon->qual = ccon->expr;
@@ -10946,7 +10946,7 @@ addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
                                               false);
            if (map)
            {
-               mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
+               mapped_pkattnum = palloc_array(AttrNumber, numfks);
                for (int j = 0; j < numfks; j++)
                    mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
            }
@@ -11081,7 +11081,7 @@ addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
 
            tab = ATGetQueueEntry(wqueue, rel);
 
-           newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+           newcon = palloc0_object(NewConstraint);
            newcon->name = get_constraint_name(parentConstr);
            newcon->contype = CONSTR_FOREIGN;
            newcon->refrelid = RelationGetRelid(pkrel);
@@ -12503,7 +12503,7 @@ ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
            AlteredTableInfo *tab;
            NewConstraint *newcon;
 
-           newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+           newcon = palloc0_object(NewConstraint);
            newcon->name = fkconstraint->conname;
            newcon->contype = CONSTR_FOREIGN;
            newcon->refrelid = currcon->confrelid;
@@ -13019,7 +13019,7 @@ QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
        /* for now this is all we need */
        fkconstraint->conname = pstrdup(NameStr(con->conname));
 
-       newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+       newcon = palloc0_object(NewConstraint);
        newcon->name = fkconstraint->conname;
        newcon->contype = CONSTR_FOREIGN;
        newcon->refrelid = con->confrelid;
@@ -13167,7 +13167,7 @@ QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
    }
 
    /* Queue validation for phase 3 */
-   newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+   newcon = palloc0_object(NewConstraint);
    newcon->name = constrName;
    newcon->contype = CONSTR_CHECK;
    newcon->refrelid = InvalidOid;
@@ -14522,7 +14522,7 @@ ATPrepAlterColumnType(List **wqueue,
         * Add a work queue item to make ATRewriteTable update the column
         * contents.
         */
-       newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+       newval = palloc0_object(NewColumnValue);
        newval->attnum = attnum;
        newval->expr = (Expr *) transform;
        newval->is_generated = false;
@@ -19262,7 +19262,7 @@ register_on_commit_action(Oid relid, OnCommitAction action)
 
    oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
-   oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
+   oc = palloc_object(OnCommitItem);
    oc->relid = relid;
    oc->oncommit = action;
    oc->creating_subid = GetCurrentSubTransactionId();
@@ -20575,8 +20575,8 @@ AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
 
    idxes = RelationGetIndexList(rel);
    attachRelIdxs = RelationGetIndexList(attachrel);
-   attachrelIdxRels = palloc(sizeof(Relation) * list_length(attachRelIdxs));
-   attachInfos = palloc(sizeof(IndexInfo *) * list_length(attachRelIdxs));
+   attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
+   attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
 
    /* Build arrays of all existing indexes and their IndexInfos */
    foreach_oid(cldIdxId, attachRelIdxs)
index 579ac8d76ae732e65bf91e3c69ee1f5f96d2a8ab..12c97f2c023b3395202f3ed5e25e0799c352de48 100644 (file)
@@ -1991,7 +1991,7 @@ RelationBuildTriggers(Relation relation)
    }
 
    /* Build trigdesc */
-   trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
+   trigdesc = palloc0_object(TriggerDesc);
    trigdesc->triggers = triggers;
    trigdesc->numtriggers = numtrigs;
    for (i = 0; i < numtrigs; i++)
@@ -2096,7 +2096,7 @@ CopyTriggerDesc(TriggerDesc *trigdesc)
    if (trigdesc == NULL || trigdesc->numtriggers <= 0)
        return NULL;
 
-   newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
+   newdesc = palloc_object(TriggerDesc);
    memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
 
    trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
@@ -4901,7 +4901,7 @@ GetAfterTriggersTableData(Oid relid, CmdType cmdType)
 
    oldcxt = MemoryContextSwitchTo(CurTransactionContext);
 
-   table = (AfterTriggersTableData *) palloc0(sizeof(AfterTriggersTableData));
+   table = palloc0_object(AfterTriggersTableData);
    table->relid = relid;
    table->cmdType = cmdType;
    qs->tables = lappend(qs->tables, table);
@@ -5050,7 +5050,7 @@ MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
    MemoryContextSwitchTo(oldcxt);
 
    /* Now build the TransitionCaptureState struct, in caller's context */
-   state = (TransitionCaptureState *) palloc0(sizeof(TransitionCaptureState));
+   state = palloc0_object(TransitionCaptureState);
    state->tcs_delete_old_table = need_old_del;
    state->tcs_update_old_table = need_old_upd;
    state->tcs_update_new_table = need_new_upd;
index dc7df736fb8267a619945c3e821afdec01f78e59..ec4580e17c9003995105075bb26ed374dac91aee 100644 (file)
@@ -1027,7 +1027,7 @@ DefineTSConfiguration(List *names, List *parameters, ObjectAddress *copied)
         * know that they will be used.
         */
        max_slots = MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_ts_config_map);
-       slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+       slot = palloc_array(TupleTableSlot *, max_slots);
 
        ScanKeyInit(&skey,
                    Anum_pg_ts_config_map_mapcfg,
@@ -1261,7 +1261,7 @@ getTokenTypes(Oid prsId, List *tokennames)
        {
            if (strcmp(strVal(val), list[j].alias) == 0)
            {
-               TSTokenTypeItem *ts = (TSTokenTypeItem *) palloc0(sizeof(TSTokenTypeItem));
+               TSTokenTypeItem *ts = palloc0_object(TSTokenTypeItem);
 
                ts->num = list[j].lexid;
                ts->name = pstrdup(strVal(val));
@@ -1344,7 +1344,7 @@ MakeConfigurationMapping(AlterTSConfigurationStmt *stmt,
     * Convert list of dictionary names to array of dict OIDs
     */
    ndict = list_length(stmt->dicts);
-   dictIds = (Oid *) palloc(sizeof(Oid) * ndict);
+   dictIds = palloc_array(Oid, ndict);
    i = 0;
    foreach(c, stmt->dicts)
    {
@@ -1432,7 +1432,7 @@ MakeConfigurationMapping(AlterTSConfigurationStmt *stmt,
        /* Allocate the slots to use and initialize them */
        nslots = Min(ntoken * ndict,
                     MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_ts_config_map));
-       slot = palloc(sizeof(TupleTableSlot *) * nslots);
+       slot = palloc_array(TupleTableSlot *, nslots);
        for (i = 0; i < nslots; i++)
            slot[i] = MakeSingleTupleTableSlot(RelationGetDescr(relMap),
                                               &TTSOpsHeapTuple);
index 47d5047fe8b1db1ca828f67786da708f4e13603f..0eb8e0a2bb03da05b70517d54a4d2ccaa6f01c30 100644 (file)
@@ -3447,10 +3447,10 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
            }
 
            /* Build the RelToCheck entry with enough space for all atts */
-           rtc = (RelToCheck *) palloc(sizeof(RelToCheck));
+           rtc = palloc_object(RelToCheck);
            rtc->rel = rel;
            rtc->natts = 0;
-           rtc->atts = (int *) palloc(sizeof(int) * RelationGetNumberOfAttributes(rel));
+           rtc->atts = palloc_array(int, RelationGetNumberOfAttributes(rel));
            result = lappend(result, rtc);
        }
 
index 6ae42ea56566828fbd6a5bfd29ca90b7468d8215..ef4de1e7fd124848091ff84d19d07236c17ee074 100644 (file)
@@ -1904,7 +1904,7 @@ AddRoleMems(Oid currentUserId, const char *rolename, Oid roleid,
        else
        {
            Oid         objectId;
-           Oid        *newmembers = palloc(sizeof(Oid));
+           Oid        *newmembers = palloc_object(Oid);
 
            /*
             * The values for these options can be taken directly from 'popt'.
@@ -2295,7 +2295,7 @@ initialize_revoke_actions(CatCList *memlist)
    if (memlist->n_members == 0)
        return NULL;
 
-   result = palloc(sizeof(RevokeRoleGrantAction) * memlist->n_members);
+   result = palloc_array(RevokeRoleGrantAction, memlist->n_members);
    for (i = 0; i < memlist->n_members; i++)
        result[i] = RRG_NOOP;
    return result;
index 0feea1d30ec36616718d9c1d80a11000644e2830..8a37c08871a0ab44c19bf820f2759cc80d6c8972 100644 (file)
@@ -268,7 +268,7 @@ parallel_vacuum_init(Relation rel, Relation *indrels, int nindexes,
    /*
     * Compute the number of parallel vacuum workers to launch
     */
-   will_parallel_vacuum = (bool *) palloc0(sizeof(bool) * nindexes);
+   will_parallel_vacuum = palloc0_array(bool, nindexes);
    parallel_workers = parallel_vacuum_compute_workers(indrels, nindexes,
                                                       nrequested_workers,
                                                       will_parallel_vacuum);
@@ -279,7 +279,7 @@ parallel_vacuum_init(Relation rel, Relation *indrels, int nindexes,
        return NULL;
    }
 
-   pvs = (ParallelVacuumState *) palloc0(sizeof(ParallelVacuumState));
+   pvs = palloc0_object(ParallelVacuumState);
    pvs->indrels = indrels;
    pvs->nindexes = nindexes;
    pvs->will_parallel_vacuum = will_parallel_vacuum;
@@ -444,7 +444,7 @@ parallel_vacuum_end(ParallelVacuumState *pvs, IndexBulkDeleteResult **istats)
 
        if (indstats->istat_updated)
        {
-           istats[i] = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+           istats[i] = palloc0_object(IndexBulkDeleteResult);
            memcpy(istats[i], &indstats->istat, sizeof(IndexBulkDeleteResult));
        }
        else
index b05ff476a6399e6a6cf3852b6dd15ef22f253988..c35744b105e592376283e84e1896a7d1400029c1 100644 (file)
@@ -1312,7 +1312,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                }
 
                /* Set up the primary fmgr lookup information */
-               finfo = palloc0(sizeof(FmgrInfo));
+               finfo = palloc0_object(FmgrInfo);
                fcinfo = palloc0(SizeForFunctionCallInfo(2));
                fmgr_info(cmpfuncid, finfo);
                fmgr_info_set_expr((Node *) node, finfo);
@@ -1388,7 +1388,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
 
                /* allocate scratch memory used by all steps of AND/OR */
                if (boolexpr->boolop != NOT_EXPR)
-                   scratch.d.boolexpr.anynull = (bool *) palloc(sizeof(bool));
+                   scratch.d.boolexpr.anynull = palloc_object(bool);
 
                /*
                 * For each argument evaluate the argument itself, then
@@ -1521,11 +1521,11 @@ ExecInitExprRec(Expr *node, ExprState *state,
                ReleaseTupleDesc(tupDesc);
 
                /* create workspace for column values */
-               values = (Datum *) palloc(sizeof(Datum) * ncolumns);
-               nulls = (bool *) palloc(sizeof(bool) * ncolumns);
+               values = palloc_array(Datum, ncolumns);
+               nulls = palloc_array(bool, ncolumns);
 
                /* create shared composite-type-lookup cache struct */
-               rowcachep = palloc(sizeof(ExprEvalRowtypeCache));
+               rowcachep = palloc_object(ExprEvalRowtypeCache);
                rowcachep->cacheptr = NULL;
 
                /* emit code to evaluate the composite input value */
@@ -1634,7 +1634,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                    scratch.opcode = EEOP_IOCOERCE_SAFE;
 
                /* lookup the source type's output function */
-               scratch.d.iocoerce.finfo_out = palloc0(sizeof(FmgrInfo));
+               scratch.d.iocoerce.finfo_out = palloc0_object(FmgrInfo);
                scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
 
                getTypeOutputInfo(exprType((Node *) iocoerce->arg),
@@ -1646,7 +1646,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                                         1, InvalidOid, NULL, NULL);
 
                /* lookup the result type's input function */
-               scratch.d.iocoerce.finfo_in = palloc0(sizeof(FmgrInfo));
+               scratch.d.iocoerce.finfo_in = palloc0_object(FmgrInfo);
                scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
 
                getTypeInputInfo(iocoerce->resulttype,
@@ -1699,8 +1699,8 @@ ExecInitExprRec(Expr *node, ExprState *state,
                elemstate->parent = state->parent;
                elemstate->ext_params = state->ext_params;
 
-               elemstate->innermost_caseval = (Datum *) palloc(sizeof(Datum));
-               elemstate->innermost_casenull = (bool *) palloc(sizeof(bool));
+               elemstate->innermost_caseval = palloc_object(Datum);
+               elemstate->innermost_casenull = palloc_object(bool);
 
                ExecInitExprRec(acoerce->elemexpr, elemstate,
                                &elemstate->resvalue, &elemstate->resnull);
@@ -1727,8 +1727,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                if (elemstate)
                {
                    /* Set up workspace for array_map */
-                   scratch.d.arraycoerce.amstate =
-                       (ArrayMapState *) palloc0(sizeof(ArrayMapState));
+                   scratch.d.arraycoerce.amstate = palloc0_object(ArrayMapState);
                }
                else
                {
@@ -1783,8 +1782,8 @@ ExecInitExprRec(Expr *node, ExprState *state,
                if (caseExpr->arg != NULL)
                {
                    /* Evaluate testexpr into caseval/casenull workspace */
-                   caseval = palloc(sizeof(Datum));
-                   casenull = palloc(sizeof(bool));
+                   caseval = palloc_object(Datum);
+                   casenull = palloc_object(bool);
 
                    ExecInitExprRec(caseExpr->arg, state,
                                    caseval, casenull);
@@ -1930,9 +1929,9 @@ ExecInitExprRec(Expr *node, ExprState *state,
                 */
                scratch.opcode = EEOP_ARRAYEXPR;
                scratch.d.arrayexpr.elemvalues =
-                   (Datum *) palloc(sizeof(Datum) * nelems);
+                   palloc_array(Datum, nelems);
                scratch.d.arrayexpr.elemnulls =
-                   (bool *) palloc(sizeof(bool) * nelems);
+                   palloc_array(bool, nelems);
                scratch.d.arrayexpr.nelems = nelems;
 
                /* fill remaining fields of step */
@@ -2006,9 +2005,9 @@ ExecInitExprRec(Expr *node, ExprState *state,
 
                /* space for the individual field datums */
                scratch.d.row.elemvalues =
-                   (Datum *) palloc(sizeof(Datum) * nelems);
+                   palloc_array(Datum, nelems);
                scratch.d.row.elemnulls =
-                   (bool *) palloc(sizeof(bool) * nelems);
+                   palloc_array(bool, nelems);
                /* as explained above, make sure any extra columns are null */
                memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
 
@@ -2109,7 +2108,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                             BTORDER_PROC, lefttype, righttype, opfamily);
 
                    /* Set up the primary fmgr lookup information */
-                   finfo = palloc0(sizeof(FmgrInfo));
+                   finfo = palloc0_object(FmgrInfo);
                    fcinfo = palloc0(SizeForFunctionCallInfo(2));
                    fmgr_info(proc, finfo);
                    fmgr_info_set_expr((Node *) node, finfo);
@@ -2252,7 +2251,7 @@ ExecInitExprRec(Expr *node, ExprState *state,
                 */
 
                /* Perform function lookup */
-               finfo = palloc0(sizeof(FmgrInfo));
+               finfo = palloc0_object(FmgrInfo);
                fcinfo = palloc0(SizeForFunctionCallInfo(2));
                fmgr_info(typentry->cmp_proc, finfo);
                fmgr_info_set_expr((Node *) node, finfo);
@@ -2261,10 +2260,8 @@ ExecInitExprRec(Expr *node, ExprState *state,
 
                scratch.opcode = EEOP_MINMAX;
                /* allocate space to store arguments */
-               scratch.d.minmax.values =
-                   (Datum *) palloc(sizeof(Datum) * nelems);
-               scratch.d.minmax.nulls =
-                   (bool *) palloc(sizeof(bool) * nelems);
+               scratch.d.minmax.values = palloc_array(Datum, nelems);
+               scratch.d.minmax.nulls = palloc_array(bool, nelems);
                scratch.d.minmax.nelems = nelems;
 
                scratch.d.minmax.op = minmaxexpr->op;
@@ -2313,10 +2310,8 @@ ExecInitExprRec(Expr *node, ExprState *state,
                /* allocate space for storing all the arguments */
                if (nnamed)
                {
-                   scratch.d.xmlexpr.named_argvalue =
-                       (Datum *) palloc(sizeof(Datum) * nnamed);
-                   scratch.d.xmlexpr.named_argnull =
-                       (bool *) palloc(sizeof(bool) * nnamed);
+                   scratch.d.xmlexpr.named_argvalue = palloc_array(Datum, nnamed);
+                   scratch.d.xmlexpr.named_argnull = palloc_array(bool, nnamed);
                }
                else
                {
@@ -2326,10 +2321,8 @@ ExecInitExprRec(Expr *node, ExprState *state,
 
                if (nargs)
                {
-                   scratch.d.xmlexpr.argvalue =
-                       (Datum *) palloc(sizeof(Datum) * nargs);
-                   scratch.d.xmlexpr.argnull =
-                       (bool *) palloc(sizeof(bool) * nargs);
+                   scratch.d.xmlexpr.argvalue = palloc_array(Datum, nargs);
+                   scratch.d.xmlexpr.argnull = palloc_array(bool, nargs);
                }
                else
                {
@@ -2398,15 +2391,15 @@ ExecInitExprRec(Expr *node, ExprState *state,
                {
                    JsonConstructorExprState *jcstate;
 
-                   jcstate = palloc0(sizeof(JsonConstructorExprState));
+                   jcstate = palloc0_object(JsonConstructorExprState);
 
                    scratch.opcode = EEOP_JSON_CONSTRUCTOR;
                    scratch.d.json_constructor.jcstate = jcstate;
 
                    jcstate->constructor = ctor;
-                   jcstate->arg_values = (Datum *) palloc(sizeof(Datum) * nargs);
-                   jcstate->arg_nulls = (bool *) palloc(sizeof(bool) * nargs);
-                   jcstate->arg_types = (Oid *) palloc(sizeof(Oid) * nargs);
+                   jcstate->arg_values = palloc_array(Datum, nargs);
+                   jcstate->arg_nulls = palloc_array(bool, nargs);
+                   jcstate->arg_types = palloc_array(Oid, nargs);
                    jcstate->nargs = nargs;
 
                    foreach(lc, args)
@@ -2680,7 +2673,7 @@ ExprEvalPushStep(ExprState *es, const ExprEvalStep *s)
    if (es->steps_alloc == 0)
    {
        es->steps_alloc = 16;
-       es->steps = palloc(sizeof(ExprEvalStep) * es->steps_alloc);
+       es->steps = palloc_array(ExprEvalStep, es->steps_alloc);
    }
    else if (es->steps_alloc == es->steps_len)
    {
@@ -2732,7 +2725,7 @@ ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args, Oid funcid,
                               FUNC_MAX_ARGS)));
 
    /* Allocate function lookup data and parameter workspace for this call */
-   scratch->d.func.finfo = palloc0(sizeof(FmgrInfo));
+   scratch->d.func.finfo = palloc0_object(FmgrInfo);
    scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
    flinfo = scratch->d.func.finfo;
    fcinfo = scratch->d.func.fcinfo_data;
@@ -3557,8 +3550,7 @@ ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
     * during executor initialization.  That means we don't need typcache.c to
     * provide compiled exprs.
     */
-   constraint_ref = (DomainConstraintRef *)
-       palloc(sizeof(DomainConstraintRef));
+   constraint_ref = palloc_object(DomainConstraintRef);
    InitDomainConstraintRef(ctest->resulttype,
                            constraint_ref,
                            CurrentMemoryContext,
@@ -3588,9 +3580,9 @@ ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
                if (scratch->d.domaincheck.checkvalue == NULL)
                {
                    scratch->d.domaincheck.checkvalue =
-                       (Datum *) palloc(sizeof(Datum));
+                       palloc_object(Datum);
                    scratch->d.domaincheck.checknull =
-                       (bool *) palloc(sizeof(bool));
+                       palloc_object(bool);
                }
 
                /*
@@ -3608,8 +3600,8 @@ ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
                        ExprEvalStep scratch2 = {0};
 
                        /* Yes, so make output workspace for MAKE_READONLY */
-                       domainval = (Datum *) palloc(sizeof(Datum));
-                       domainnull = (bool *) palloc(sizeof(bool));
+                       domainval = palloc_object(Datum);
+                       domainnull = palloc_object(bool);
 
                        /* Emit MAKE_READONLY */
                        scratch2.opcode = EEOP_MAKE_READONLY;
@@ -4159,7 +4151,7 @@ ExecBuildHash32FromAttrs(TupleDesc desc, const TupleTableSlotOps *ops,
     * one column to hash or an initial value plus one column.
     */
    if ((int64) numCols + (init_value != 0) > 1)
-       iresult = palloc(sizeof(NullableDatum));
+       iresult = palloc_object(NullableDatum);
 
    /* find the highest attnum so we deform the tuple to that point */
    for (int i = 0; i < numCols; i++)
@@ -4325,7 +4317,7 @@ ExecBuildHash32Expr(TupleDesc desc, const TupleTableSlotOps *ops,
     * than one expression to hash or an initial value plus one expression.
     */
    if ((int64) num_exprs + (init_value != 0) > 1)
-       iresult = palloc(sizeof(NullableDatum));
+       iresult = palloc_object(NullableDatum);
 
    if (init_value == 0)
    {
@@ -4371,7 +4363,7 @@ ExecBuildHash32Expr(TupleDesc desc, const TupleTableSlotOps *ops,
        funcid = hashfunc_oids[i];
 
        /* Allocate hash function lookup data. */
-       finfo = palloc0(sizeof(FmgrInfo));
+       finfo = palloc0_object(FmgrInfo);
        fcinfo = palloc0(SizeForFunctionCallInfo(1));
 
        fmgr_info(funcid, finfo);
@@ -4540,7 +4532,7 @@ ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc,
        InvokeFunctionExecuteHook(foid);
 
        /* Set up the primary fmgr lookup information */
-       finfo = palloc0(sizeof(FmgrInfo));
+       finfo = palloc0_object(FmgrInfo);
        fcinfo = palloc0(SizeForFunctionCallInfo(2));
        fmgr_info(foid, finfo);
        fmgr_info_set_expr(NULL, finfo);
@@ -4676,7 +4668,7 @@ ExecBuildParamSetEqual(TupleDesc desc,
        InvokeFunctionExecuteHook(foid);
 
        /* Set up the primary fmgr lookup information */
-       finfo = palloc0(sizeof(FmgrInfo));
+       finfo = palloc0_object(FmgrInfo);
        fcinfo = palloc0(SizeForFunctionCallInfo(2));
        fmgr_info(foid, finfo);
        fmgr_info_set_expr(NULL, finfo);
@@ -4749,7 +4741,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
                 Datum *resv, bool *resnull,
                 ExprEvalStep *scratch)
 {
-   JsonExprState *jsestate = palloc0(sizeof(JsonExprState));
+   JsonExprState *jsestate = palloc0_object(JsonExprState);
    ListCell   *argexprlc;
    ListCell   *argnamelc;
    List       *jumps_return_null = NIL;
@@ -4800,7 +4792,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
    {
        Expr       *argexpr = (Expr *) lfirst(argexprlc);
        String     *argname = lfirst_node(String, argnamelc);
-       JsonPathVariable *var = palloc(sizeof(*var));
+       JsonPathVariable *var = palloc_object(JsonPathVariable);
 
        var->name = argname->sval;
        var->namelen = strlen(var->name);
@@ -4874,7 +4866,7 @@ ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
        FunctionCallInfo fcinfo;
 
        getTypeInputInfo(jsexpr->returning->typid, &typinput, &typioparam);
-       finfo = palloc0(sizeof(FmgrInfo));
+       finfo = palloc0_object(FmgrInfo);
        fcinfo = palloc0(SizeForFunctionCallInfo(3));
        fmgr_info(typinput, finfo);
        fmgr_info_set_expr((Node *) jsexpr->returning, finfo);
index 8b64a625ca5533490d033ec76521798e865b74ab..8eb4c25e1cb0ff0d15acd1914888686d41bd1816 100644 (file)
@@ -224,7 +224,7 @@ BuildTupleHashTable(PlanState *parent,
 
    oldcontext = MemoryContextSwitchTo(metacxt);
 
-   hashtable = (TupleHashTable) palloc(sizeof(TupleHashTableData));
+   hashtable = palloc_object(TupleHashTableData);
 
    hashtable->numCols = numCols;
    hashtable->keyColIdx = keyColIdx;
index dd323c9b9fd42787ba1ca9e52c1b86349000c2f6..0b3a31f170351373a28c10546bbb50a862bf8f09 100644 (file)
@@ -188,8 +188,8 @@ ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
    /*
     * allocate space for result arrays
     */
-   relationDescs = (RelationPtr) palloc(len * sizeof(Relation));
-   indexInfoArray = (IndexInfo **) palloc(len * sizeof(IndexInfo *));
+   relationDescs = palloc_array(Relation, len);
+   indexInfoArray = palloc_array(IndexInfo *, len);
 
    resultRelInfo->ri_NumIndices = len;
    resultRelInfo->ri_IndexRelationDescs = relationDescs;
index 27c9eec697b188941b767054eb868429b0990dd0..797d8b1ca1cbc166cbc97dd7797fa1ac109196b6 100644 (file)
@@ -189,7 +189,7 @@ standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
 
        nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
        estate->es_param_exec_vals = (ParamExecData *)
-           palloc0(nParamExec * sizeof(ParamExecData));
+           palloc0_array(ParamExecData, nParamExec);
    }
 
    /* We now require all callers to provide sourceText */
@@ -876,7 +876,7 @@ InitPlan(QueryDesc *queryDesc, int eflags)
    if (plannedstmt->rowMarks)
    {
        estate->es_rowmarks = (ExecRowMark **)
-           palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
+           palloc0_array(ExecRowMark *, estate->es_range_table_size);
        foreach(l, plannedstmt->rowMarks)
        {
            PlanRowMark *rc = (PlanRowMark *) lfirst(l);
@@ -920,7 +920,7 @@ InitPlan(QueryDesc *queryDesc, int eflags)
            if (relation)
                CheckValidRowMarkRel(relation, rc->markType);
 
-           erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
+           erm = palloc_object(ExecRowMark);
            erm->relation = relation;
            erm->relid = relid;
            erm->rti = rc->rti;
@@ -1262,9 +1262,9 @@ InitResultRelInfo(ResultRelInfo *resultRelInfo,
        int         n = resultRelInfo->ri_TrigDesc->numtriggers;
 
        resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
-           palloc0(n * sizeof(FmgrInfo));
+           palloc0_array(FmgrInfo, n);
        resultRelInfo->ri_TrigWhenExprs = (ExprState **)
-           palloc0(n * sizeof(ExprState *));
+           palloc0_array(ExprState *, n);
        if (instrument_options)
            resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
    }
@@ -2578,7 +2578,7 @@ ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
 ExecAuxRowMark *
 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
 {
-   ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
+   ExecAuxRowMark *aerm = palloc0_object(ExecAuxRowMark);
    char        resname[32];
 
    aerm->rowmark = erm;
@@ -2734,8 +2734,7 @@ EvalPlanQualInit(EPQState *epqstate, EState *parentestate,
     * EvalPlanQualBegin().
     */
    epqstate->tuple_table = NIL;
-   epqstate->relsubs_slot = (TupleTableSlot **)
-       palloc0(rtsize * sizeof(TupleTableSlot *));
+   epqstate->relsubs_slot = palloc0_array(TupleTableSlot *, rtsize);
 
    /* ... and remember data that EvalPlanQualBegin will need */
    epqstate->plan = subplan;
@@ -3074,8 +3073,7 @@ EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
 
        /* now make the internal param workspace ... */
        i = list_length(parentestate->es_plannedstmt->paramExecTypes);
-       rcestate->es_param_exec_vals = (ParamExecData *)
-           palloc0(i * sizeof(ParamExecData));
+       rcestate->es_param_exec_vals = palloc0_array(ParamExecData, i);
        /* ... and copy down all values, whether really needed or not */
        while (--i >= 0)
        {
@@ -3130,8 +3128,7 @@ EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
     * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
     * rowmark.
     */
-   epqstate->relsubs_rowmark = (ExecAuxRowMark **)
-       palloc0(rtsize * sizeof(ExecAuxRowMark *));
+   epqstate->relsubs_rowmark = palloc0_array(ExecAuxRowMark *, rtsize);
    foreach(l, epqstate->arowMarks)
    {
        ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
index 0125464d942b08ffee3e3008f9b40d41070c16df..26200c5a3d6e5ec0cb4e1fe9889aa7d6ef9221f8 100644 (file)
@@ -647,7 +647,7 @@ ExecInitParallelPlan(PlanState *planstate, EState *estate,
    ExecSetParamPlanMulti(sendParams, GetPerTupleExprContext(estate));
 
    /* Allocate object for return value. */
-   pei = palloc0(sizeof(ParallelExecutorInfo));
+   pei = palloc0_object(ParallelExecutorInfo);
    pei->finished = false;
    pei->planstate = planstate;
 
index def32774c90db6f2493d4f217e4df27531b7d2a5..860f79f9cc1a0df6a12d41c1ba8ed18c86f434f1 100644 (file)
@@ -221,7 +221,7 @@ retry:
        if (!isIdxSafeToSkipDuplicates)
        {
            if (eq == NULL)
-               eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
+               eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
 
            if (!tuples_equal(outslot, searchslot, eq, NULL))
                continue;
@@ -378,7 +378,7 @@ RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode,
 
    Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor));
 
-   eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
+   eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
 
    /* Start a heap scan. */
    InitDirtySnapshot(snap);
@@ -593,7 +593,7 @@ RelationFindDeletedTupleInfoSeq(Relation rel, TupleTableSlot *searchslot,
        indexbitmap = RelationGetIndexAttrBitmap(rel,
                                                 INDEX_ATTR_BITMAP_PRIMARY_KEY);
 
-   eq = palloc0(sizeof(*eq) * searchslot->tts_tupleDescriptor->natts);
+   eq = palloc0_array(TypeCacheEntry *, searchslot->tts_tupleDescriptor->natts);
 
    /*
     * Start a heap scan using SnapshotAny to identify dead tuples that are
@@ -679,7 +679,7 @@ RelationFindDeletedTupleInfoByIndex(Relation rel, Oid idxoid,
        if (!isIdxSafeToSkipDuplicates)
        {
            if (eq == NULL)
-               eq = palloc0(sizeof(*eq) * scanslot->tts_tupleDescriptor->natts);
+               eq = palloc0_array(TypeCacheEntry *, scanslot->tts_tupleDescriptor->natts);
 
            if (!tuples_equal(scanslot, searchslot, eq, NULL))
                continue;
index 8e02d68824fad80a2c39b926a37547c9e5bcc7ba..b0dc2cfa66f9ff5afff55e43ad4f7a30a142f283 100644 (file)
@@ -2283,7 +2283,7 @@ TupleDescGetAttInMetadata(TupleDesc tupdesc)
    int32      *atttypmods;
    AttInMetadata *attinmeta;
 
-   attinmeta = (AttInMetadata *) palloc(sizeof(AttInMetadata));
+   attinmeta = palloc_object(AttInMetadata);
 
    /* "Bless" the tupledesc so that we can make rowtype datums with it */
    attinmeta->tupdesc = BlessTupleDesc(tupdesc);
@@ -2447,7 +2447,7 @@ begin_tup_output_tupdesc(DestReceiver *dest,
 {
    TupOutputState *tstate;
 
-   tstate = (TupOutputState *) palloc(sizeof(TupOutputState));
+   tstate = palloc_object(TupOutputState);
 
    tstate->slot = MakeSingleTupleTableSlot(tupdesc, tts_ops);
    tstate->dest = dest;
index 630d708d2a3f0aa6c6b1e5a9a2a531033d9f4cc9..d9cc723daa0d169f5999f8945bd0dae78b41b028 100644 (file)
@@ -256,7 +256,7 @@ prepare_sql_fn_parse_info(HeapTuple procedureTuple,
    Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
    int         nargs;
 
-   pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
+   pinfo = (SQLFunctionParseInfoPtr) palloc0_object(SQLFunctionParseInfo);
 
    /* Function's name (only) can be used to qualify argument names */
    pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
@@ -2616,7 +2616,7 @@ get_sql_fn_result_tlist(List *queryTreeList)
 DestReceiver *
 CreateSQLFunctionDestReceiver(void)
 {
-   DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
+   DR_sqlfunction *self = palloc0_object(DR_sqlfunction);
 
    self->pub.receiveSlot = sqlfunction_receive;
    self->pub.rStartup = sqlfunction_startup;
index 0b02fd321075cd9af28270c4712c8cd0664f5ae6..a18556f62eccafa983fc056d7b516c50a93a1265 100644 (file)
@@ -1920,7 +1920,7 @@ hash_agg_enter_spill_mode(AggState *aggstate)
 
        aggstate->hash_tapeset = LogicalTapeSetCreate(true, NULL, -1);
 
-       aggstate->hash_spills = palloc(sizeof(HashAggSpill) * aggstate->num_hashes);
+       aggstate->hash_spills = palloc_array(HashAggSpill, aggstate->num_hashes);
 
        for (int setno = 0; setno < aggstate->num_hashes; setno++)
        {
@@ -2999,9 +2999,9 @@ hashagg_spill_init(HashAggSpill *spill, LogicalTapeSet *tapeset, int used_bits,
    }
 #endif
 
-   spill->partitions = palloc0(sizeof(LogicalTape *) * npartitions);
-   spill->ntuples = palloc0(sizeof(int64) * npartitions);
-   spill->hll_card = palloc0(sizeof(hyperLogLogState) * npartitions);
+   spill->partitions = palloc0_array(LogicalTape *, npartitions);
+   spill->ntuples = palloc0_array(int64, npartitions);
+   spill->hll_card = palloc0_array(hyperLogLogState, npartitions);
 
    for (int i = 0; i < npartitions; i++)
        spill->partitions[i] = LogicalTapeCreate(tapeset);
@@ -3097,7 +3097,7 @@ static HashAggBatch *
 hashagg_batch_new(LogicalTape *input_tape, int setno,
                  int64 input_tuples, double input_card, int used_bits)
 {
-   HashAggBatch *batch = palloc0(sizeof(HashAggBatch));
+   HashAggBatch *batch = palloc0_object(HashAggBatch);
 
    batch->setno = setno;
    batch->used_bits = used_bits;
@@ -3368,8 +3368,7 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
    aggstate->maxsets = numGroupingSets;
    aggstate->numphases = numPhases;
 
-   aggstate->aggcontexts = (ExprContext **)
-       palloc0(sizeof(ExprContext *) * numGroupingSets);
+   aggstate->aggcontexts = palloc0_array(ExprContext *, numGroupingSets);
 
    /*
     * Create expression contexts.  We need three or more, one for
@@ -3492,15 +3491,15 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
     * For each phase, prepare grouping set data and fmgr lookup data for
     * compare functions.  Accumulate all_grouped_cols in passing.
     */
-   aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
+   aggstate->phases = palloc0_array(AggStatePerPhaseData, numPhases);
 
    aggstate->num_hashes = numHashes;
    if (numHashes)
    {
-       aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
+       aggstate->perhash = palloc0_array(AggStatePerHashData, numHashes);
        aggstate->phases[0].numsets = 0;
-       aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
-       aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
+       aggstate->phases[0].gset_lengths = palloc_array(int, numHashes);
+       aggstate->phases[0].grouped_cols = palloc_array(Bitmapset *, numHashes);
    }
 
    phase = 0;
@@ -3598,8 +3597,7 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
                 * Build a separate function for each subset of columns that
                 * need to be compared.
                 */
-               phasedata->eqfunctions =
-                   (ExprState **) palloc0(aggnode->numCols * sizeof(ExprState *));
+               phasedata->eqfunctions = palloc0_array(ExprState *, aggnode->numCols);
 
                /* for each grouping set */
                for (int k = 0; k < phasedata->numsets; k++)
@@ -3655,27 +3653,24 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
     * allocate my private per-agg working storage
     */
    econtext = aggstate->ss.ps.ps_ExprContext;
-   econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
-   econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
+   econtext->ecxt_aggvalues = palloc0_array(Datum, numaggs);
+   econtext->ecxt_aggnulls = palloc0_array(bool, numaggs);
 
-   peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
-   pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numtrans);
+   peraggs = palloc0_array(AggStatePerAggData, numaggs);
+   pertransstates = palloc0_array(AggStatePerTransData, numtrans);
 
    aggstate->peragg = peraggs;
    aggstate->pertrans = pertransstates;
 
 
-   aggstate->all_pergroups =
-       (AggStatePerGroup *) palloc0(sizeof(AggStatePerGroup)
-                                    * (numGroupingSets + numHashes));
+   aggstate->all_pergroups = palloc0_array(AggStatePerGroup, numGroupingSets + numHashes);
    pergroups = aggstate->all_pergroups;
 
    if (node->aggstrategy != AGG_HASHED)
    {
        for (i = 0; i < numGroupingSets; i++)
        {
-           pergroups[i] = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
-                                                     * numaggs);
+           pergroups[i] = palloc0_array(AggStatePerGroupData, numaggs);
        }
 
        aggstate->pergroups = pergroups;
@@ -4375,8 +4370,7 @@ build_pertrans_for_aggref(AggStatePerTrans pertrans,
        pfree(ops);
    }
 
-   pertrans->sortstates = (Tuplesortstate **)
-       palloc0(sizeof(Tuplesortstate *) * numGroupingSets);
+   pertrans->sortstates = palloc0_array(Tuplesortstate *, numGroupingSets);
 }
 
 
index a11b36c7176621b8fd5807265091d368606a2850..77c4dd9e4b18f338e6a3773b2fc97c3f0e83c0ad 100644 (file)
@@ -263,7 +263,7 @@ ExecInitAppend(Append *node, EState *estate, int eflags)
        {
            AsyncRequest *areq;
 
-           areq = palloc(sizeof(AsyncRequest));
+           areq = palloc_object(AsyncRequest);
            areq->requestor = (PlanState *) appendstate;
            areq->requestee = appendplanstates[i];
            areq->request_index = i;
index 644363582d913dbea2305026e12d58bf3998caef..af75dd8fc5e5da937c08bfb7ee0b01db530f922c 100644 (file)
@@ -333,7 +333,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags)
     */
    ExecAssignExprContext(estate, &scanstate->ss.ps);
 
-   scanstate->funcstates = palloc(nfuncs * sizeof(FunctionScanPerFuncState));
+   scanstate->funcstates = palloc_array(FunctionScanPerFuncState, nfuncs);
 
    natts = 0;
    i = 0;
index 93f3dbc6cf486b3de8dcb0ef7387773febfbdedf..c04522fea4d9eebaa6cc1dfb81e62702db6d6a26 100644 (file)
@@ -145,8 +145,7 @@ ExecInitGatherMerge(GatherMerge *node, EState *estate, int eflags)
        int         i;
 
        gm_state->gm_nkeys = node->numCols;
-       gm_state->gm_sortkeys =
-           palloc0(sizeof(SortSupportData) * node->numCols);
+       gm_state->gm_sortkeys = palloc0_array(SortSupportData, node->numCols);
 
        for (i = 0; i < node->numCols; i++)
        {
@@ -418,8 +417,7 @@ gather_merge_setup(GatherMergeState *gm_state)
    for (i = 0; i < nreaders; i++)
    {
        /* Allocate the tuple array with length MAX_TUPLE_STORE */
-       gm_state->gm_tuple_buffers[i].tuple =
-           (MinimalTuple *) palloc0(sizeof(MinimalTuple) * MAX_TUPLE_STORE);
+       gm_state->gm_tuple_buffers[i].tuple = palloc0_array(MinimalTuple, MAX_TUPLE_STORE);
 
        /* Initialize tuple slot for worker */
        gm_state->gm_slots[i + 1] =
index 5661ad768300422ddefac06a9ae5b79a5e5d06c4..cc50bee19eb9369c6d83ff85364dc64f1e1c2ec9 100644 (file)
@@ -899,7 +899,7 @@ ExecInitHashJoin(HashJoin *node, EState *estate, int eflags)
         */
        if (OidIsValid(hash->skewTable))
        {
-           hashstate->skew_hashfunction = palloc0(sizeof(FmgrInfo));
+           hashstate->skew_hashfunction = palloc0_object(FmgrInfo);
            hashstate->skew_collation = linitial_oid(node->hashcollations);
            fmgr_info(outer_hashfuncid[0], hashstate->skew_hashfunction);
        }
@@ -1541,8 +1541,7 @@ ExecReScanHashJoin(HashJoinState *node)
            /* accumulate stats from old hash table, if wanted */
            /* (this should match ExecShutdownHash) */
            if (hashNode->ps.instrument && !hashNode->hinstrument)
-               hashNode->hinstrument = (HashInstrumentation *)
-                   palloc0(sizeof(HashInstrumentation));
+               hashNode->hinstrument = palloc0_object(HashInstrumentation);
            if (hashNode->hinstrument)
                ExecHashAccumInstrumentation(hashNode->hinstrument,
                                             hashNode->hashtable);
index f464cca9507a54b2b36c09ca3453c97333797f3e..6bea42f128ff1a9dfe65f37db07079fcc28b6446 100644 (file)
@@ -693,8 +693,7 @@ ExecInitIndexOnlyScan(IndexOnlyScan *node, EState *estate, int eflags)
         * Now create an array to mark the attribute numbers of the keys that
         * need to be converted from cstring to name.
         */
-       indexstate->ioss_NameCStringAttNums = (AttrNumber *)
-           palloc(sizeof(AttrNumber) * namecount);
+       indexstate->ioss_NameCStringAttNums = palloc_array(AttrNumber, namecount);
 
        for (int attnum = 0; attnum < indnkeyatts; attnum++)
        {
index f36929deec338b8f6c2a4df9fc3e8c15f8070393..72b135e5dcf05465b581277c95f13bfe860efedc 100644 (file)
@@ -466,12 +466,10 @@ reorderqueue_push(IndexScanState *node, TupleTableSlot *slot,
    ReorderTuple *rt;
    int         i;
 
-   rt = (ReorderTuple *) palloc(sizeof(ReorderTuple));
+   rt = palloc_object(ReorderTuple);
    rt->htup = ExecCopySlotHeapTuple(slot);
-   rt->orderbyvals =
-       (Datum *) palloc(sizeof(Datum) * scandesc->numberOfOrderBys);
-   rt->orderbynulls =
-       (bool *) palloc(sizeof(bool) * scandesc->numberOfOrderBys);
+   rt->orderbyvals = palloc_array(Datum, scandesc->numberOfOrderBys);
+   rt->orderbynulls = palloc_array(bool, scandesc->numberOfOrderBys);
    for (i = 0; i < node->iss_NumOrderByKeys; i++)
    {
        if (!orderbynulls[i])
index d652663cb6a99b53b35ca6a4f4693795235e7342..7444391e8a194a3eb8d93fe92494994cf6a26a60 100644 (file)
@@ -555,7 +555,7 @@ cache_lookup(MemoizeState *mstate, bool *found)
    oldcontext = MemoryContextSwitchTo(mstate->tableContext);
 
    /* Allocate a new key */
-   entry->key = key = (MemoizeKey *) palloc(sizeof(MemoizeKey));
+   entry->key = key = palloc_object(MemoizeKey);
    key->params = ExecCopySlotMinimalTuple(mstate->probeslot);
 
    /* Update the total cache memory utilization */
@@ -634,7 +634,7 @@ cache_store_tuple(MemoizeState *mstate, TupleTableSlot *slot)
 
    oldcontext = MemoryContextSwitchTo(mstate->tableContext);
 
-   tuple = (MemoizeTuple *) palloc(sizeof(MemoizeTuple));
+   tuple = palloc_object(MemoizeTuple);
    tuple->mintuple = ExecCopySlotMinimalTuple(slot);
    tuple->next = NULL;
 
index 405e8f942857f3b2713163293cbb678d9e7388e5..300bcd5cf33a9e310992dfb76a282dccbcce6ae0 100644 (file)
@@ -122,11 +122,11 @@ ExecInitMergeAppend(MergeAppend *node, EState *estate, int eflags)
        mergestate->ms_prune_state = NULL;
    }
 
-   mergeplanstates = (PlanState **) palloc(nplans * sizeof(PlanState *));
+   mergeplanstates = palloc_array(PlanState *, nplans);
    mergestate->mergeplans = mergeplanstates;
    mergestate->ms_nplans = nplans;
 
-   mergestate->ms_slots = (TupleTableSlot **) palloc0(sizeof(TupleTableSlot *) * nplans);
+   mergestate->ms_slots = palloc0_array(TupleTableSlot *, nplans);
    mergestate->ms_heap = binaryheap_allocate(nplans, heap_compare_slots,
                                              mergestate);
 
@@ -174,7 +174,7 @@ ExecInitMergeAppend(MergeAppend *node, EState *estate, int eflags)
     * initialize sort-key information
     */
    mergestate->ms_nkeys = node->numCols;
-   mergestate->ms_sortkeys = palloc0(sizeof(SortSupportData) * node->numCols);
+   mergestate->ms_sortkeys = palloc0_array(SortSupportData, node->numCols);
 
    for (i = 0; i < node->numCols; i++)
    {
index e44f12238864fbca1968b8c131b600a93d9b22ca..874b71e6608ea3de543f1a7922a731eac576aa99 100644 (file)
@@ -581,8 +581,8 @@ ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo,
 
    oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 
-   values = palloc(sizeof(*values) * natts);
-   nulls = palloc(sizeof(*nulls) * natts);
+   values = palloc_array(Datum, natts);
+   nulls = palloc_array(bool, natts);
 
    slot_getallattrs(slot);
    memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
@@ -962,10 +962,8 @@ ExecInsert(ModifyTableContext *context,
 
            if (resultRelInfo->ri_Slots == NULL)
            {
-               resultRelInfo->ri_Slots = palloc(sizeof(TupleTableSlot *) *
-                                                resultRelInfo->ri_BatchSize);
-               resultRelInfo->ri_PlanSlots = palloc(sizeof(TupleTableSlot *) *
-                                                    resultRelInfo->ri_BatchSize);
+               resultRelInfo->ri_Slots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
+               resultRelInfo->ri_PlanSlots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
            }
 
            /*
@@ -4745,8 +4743,7 @@ ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
    mtstate->mt_done = false;
 
    mtstate->mt_nrels = nrels;
-   mtstate->resultRelInfo = (ResultRelInfo *)
-       palloc(nrels * sizeof(ResultRelInfo));
+   mtstate->resultRelInfo = palloc_array(ResultRelInfo, nrels);
 
    mtstate->mt_merge_pending_not_matched = NULL;
    mtstate->mt_merge_inserted = 0;
index 880f39fb2ff1e60b45c1415f6553150ad99f3d0c..7d621cebc7bc6acd46e00d323a93f2c710eb7fc1 100644 (file)
@@ -267,10 +267,8 @@ ExecInitProjectSet(ProjectSet *node, EState *estate, int eflags)
 
    /* Create workspace for per-tlist-entry expr state & SRF-is-done state */
    state->nelems = list_length(node->plan.targetlist);
-   state->elems = (Node **)
-       palloc(sizeof(Node *) * state->nelems);
-   state->elemdone = (ExprDoneCond *)
-       palloc(sizeof(ExprDoneCond) * state->nelems);
+   state->elems = palloc_array(Node *, state->nelems);
+   state->elemdone = palloc_array(ExprDoneCond, state->nelems);
 
    /*
     * Build expressions to evaluate targetlist.  We can't use
index 6b3db7548ed99ec0bf23dc1c18690ffe494aac03..c28bc6fc62044ecf8870e9382fc7d9b6a90ebf7a 100644 (file)
@@ -228,7 +228,7 @@ tablesample_init(SampleScanState *scanstate)
    ListCell   *arg;
 
    scanstate->donetuples = 0;
-   params = (Datum *) palloc(list_length(scanstate->args) * sizeof(Datum));
+   params = palloc_array(Datum, list_length(scanstate->args));
 
    i = 0;
    foreach(arg, scanstate->args)
index 4bae685d45a899bbd54feb5dbe45d5c18dc95989..4abada0e03e0ffd2a477d3540d5207d1a4a3183d 100644 (file)
@@ -192,8 +192,8 @@ ExecInitTableFuncScan(TableFuncScan *node, EState *estate, int eflags)
    scanstate->notnulls = tf->notnulls;
 
    /* these are allocated now and initialized later */
-   scanstate->in_functions = palloc(sizeof(FmgrInfo) * tupdesc->natts);
-   scanstate->typioparams = palloc(sizeof(Oid) * tupdesc->natts);
+   scanstate->in_functions = palloc_array(FmgrInfo, tupdesc->natts);
+   scanstate->typioparams = palloc_array(Oid, tupdesc->natts);
 
    /*
     * Fill in the necessary fmgr infos.
index 6fd9f68cddd4f8c2d73d3ccbb5d77d988d305b15..4ceb181d622c0a5b3ea22071237b9a282e1baf54 100644 (file)
@@ -72,7 +72,7 @@ MakeTidOpExpr(OpExpr *expr, TidRangeScanState *tidstate)
    else
        elog(ERROR, "could not identify CTID variable");
 
-   tidopexpr = (TidOpExpr *) palloc(sizeof(TidOpExpr));
+   tidopexpr = palloc_object(TidOpExpr);
    tidopexpr->inclusive = false;   /* for now */
 
    switch (expr->opno)
index d50c6600358c5ff9925b8ea55f3fe44925e5ae6c..35fcd5625db320f01d7e408386fa8116b636d1c6 100644 (file)
@@ -78,7 +78,7 @@ TidExprListCreate(TidScanState *tidstate)
    foreach(l, node->tidquals)
    {
        Expr       *expr = (Expr *) lfirst(l);
-       TidExpr    *tidexpr = (TidExpr *) palloc0(sizeof(TidExpr));
+       TidExpr    *tidexpr = palloc0_object(TidExpr);
 
        if (is_opclause(expr))
        {
index 3a0d1f0c92264c7cadce556ac64a12910a393954..c0e5ab8dbbf09ea4ed5a32f2519647547661828c 100644 (file)
@@ -2661,14 +2661,14 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
    numfuncs = winstate->numfuncs;
    numaggs = winstate->numaggs;
    econtext = winstate->ss.ps.ps_ExprContext;
-   econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numfuncs);
-   econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numfuncs);
+   econtext->ecxt_aggvalues = palloc0_array(Datum, numfuncs);
+   econtext->ecxt_aggnulls = palloc0_array(bool, numfuncs);
 
    /*
     * allocate per-wfunc/per-agg state information.
     */
-   perfunc = (WindowStatePerFunc) palloc0(sizeof(WindowStatePerFuncData) * numfuncs);
-   peragg = (WindowStatePerAgg) palloc0(sizeof(WindowStatePerAggData) * numaggs);
+   perfunc = palloc0_array(WindowStatePerFuncData, numfuncs);
+   peragg = palloc0_array(WindowStatePerAggData, numaggs);
    winstate->perfunc = perfunc;
    winstate->peragg = peragg;
 
@@ -3467,8 +3467,8 @@ init_notnull_info(WindowObject winobj, WindowStatePerFunc perfuncstate)
 
    if (winobj->ignore_nulls == PARSER_IGNORE_NULLS)
    {
-       winobj->notnull_info = palloc0(sizeof(uint8 *) * numargs);
-       winobj->num_notnull_info = palloc0(sizeof(int64) * numargs);
+       winobj->notnull_info = palloc0_array(uint8 *, numargs);
+       winobj->num_notnull_info = palloc0_array(int64, numargs);
    }
 }
 
index 653500b38dc945345efa2d7cc137c5e8a912b974..34a63a977b6e4a520c13514462419576fa48e59a 100644 (file)
@@ -1130,8 +1130,8 @@ SPI_modifytuple(Relation rel, HeapTuple tuple, int natts, int *attnum,
    SPI_result = 0;
 
    numberOfAttributes = rel->rd_att->natts;
-   v = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
-   n = (bool *) palloc(numberOfAttributes * sizeof(bool));
+   v = palloc_array(Datum, numberOfAttributes);
+   n = palloc_array(bool, numberOfAttributes);
 
    /* fetch old values and nulls */
    heap_deform_tuple(tuple, rel->rd_att, v, n);
@@ -2141,8 +2141,7 @@ spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
                                      ALLOCSET_DEFAULT_SIZES);
    MemoryContextSwitchTo(tuptabcxt);
 
-   _SPI_current->tuptable = tuptable = (SPITupleTable *)
-       palloc0(sizeof(SPITupleTable));
+   _SPI_current->tuptable = tuptable = palloc0_object(SPITupleTable);
    tuptable->tuptabcxt = tuptabcxt;
    tuptable->subid = GetCurrentSubTransactionId();
 
@@ -2155,7 +2154,7 @@ spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
 
    /* set up initial allocations */
    tuptable->alloced = 128;
-   tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
+   tuptable->vals = palloc_array(HeapTuple, tuptable->alloced);
    tuptable->numvals = 0;
    tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
 
@@ -3162,7 +3161,7 @@ _SPI_make_plan_non_temp(SPIPlanPtr plan)
    oldcxt = MemoryContextSwitchTo(plancxt);
 
    /* Copy the _SPI_plan struct and subsidiary data into the new context */
-   newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
+   newplan = palloc0_object(_SPI_plan);
    newplan->magic = _SPI_PLAN_MAGIC;
    newplan->plancxt = plancxt;
    newplan->parse_mode = plan->parse_mode;
@@ -3170,7 +3169,7 @@ _SPI_make_plan_non_temp(SPIPlanPtr plan)
    newplan->nargs = plan->nargs;
    if (plan->nargs > 0)
    {
-       newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
+       newplan->argtypes = palloc_array(Oid, plan->nargs);
        memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
    }
    else
@@ -3227,7 +3226,7 @@ _SPI_save_plan(SPIPlanPtr plan)
    oldcxt = MemoryContextSwitchTo(plancxt);
 
    /* Copy the SPI plan into its own context */
-   newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
+   newplan = palloc0_object(_SPI_plan);
    newplan->magic = _SPI_PLAN_MAGIC;
    newplan->plancxt = plancxt;
    newplan->parse_mode = plan->parse_mode;
@@ -3235,7 +3234,7 @@ _SPI_save_plan(SPIPlanPtr plan)
    newplan->nargs = plan->nargs;
    if (plan->nargs > 0)
    {
-       newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
+       newplan->argtypes = palloc_array(Oid, plan->nargs);
        memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
    }
    else
@@ -3369,7 +3368,7 @@ SPI_register_trigger_data(TriggerData *tdata)
    if (tdata->tg_newtable)
    {
        EphemeralNamedRelation enr =
-           palloc(sizeof(EphemeralNamedRelationData));
+           palloc_object(EphemeralNamedRelationData);
        int         rc;
 
        enr->md.name = tdata->tg_trigger->tgnewtable;
@@ -3386,7 +3385,7 @@ SPI_register_trigger_data(TriggerData *tdata)
    if (tdata->tg_oldtable)
    {
        EphemeralNamedRelation enr =
-           palloc(sizeof(EphemeralNamedRelationData));
+           palloc_object(EphemeralNamedRelationData);
        int         rc;
 
        enr->md.name = tdata->tg_trigger->tgoldtable;
index 6c5e1f1262d8226e498166370e18d1fd583918c5..d9bf59f672d578095287b9ca7fa1a6eb37832a2d 100644 (file)
@@ -120,7 +120,7 @@ CreateTupleQueueDestReceiver(shm_mq_handle *handle)
 {
    TQueueDestReceiver *self;
 
-   self = (TQueueDestReceiver *) palloc0(sizeof(TQueueDestReceiver));
+   self = palloc0_object(TQueueDestReceiver);
 
    self->pub.receiveSlot = tqueueReceiveSlot;
    self->pub.rStartup = tqueueStartupReceiver;
@@ -138,7 +138,7 @@ CreateTupleQueueDestReceiver(shm_mq_handle *handle)
 TupleQueueReader *
 CreateTupleQueueReader(shm_mq_handle *handle)
 {
-   TupleQueueReader *reader = palloc0(sizeof(TupleQueueReader));
+   TupleQueueReader *reader = palloc0_object(TupleQueueReader);
 
    reader->queue = handle;
 
index 02a3ad3aa680789866d770cc99d71d38bd93ef3c..2012618e230feeba703a13776292f806eb19627c 100644 (file)
@@ -238,7 +238,7 @@ tstoreDestroyReceiver(DestReceiver *self)
 DestReceiver *
 CreateTuplestoreDestReceiver(void)
 {
-   TStoreState *self = (TStoreState *) palloc0(sizeof(TStoreState));
+   TStoreState *self = palloc0_object(TStoreState);
 
    self->pub.receiveSlot = tstoreReceiveSlot_notoast;  /* might change */
    self->pub.rStartup = tstoreStartupReceiver;
index a57e59f27ea64f37117580e9a79d783fe08e4e79..fa3f4c75247514c3e248d313df570617939ad4df 100644 (file)
@@ -66,7 +66,7 @@ GetForeignDataWrapperExtended(Oid fdwid, bits16 flags)
 
    fdwform = (Form_pg_foreign_data_wrapper) GETSTRUCT(tp);
 
-   fdw = (ForeignDataWrapper *) palloc(sizeof(ForeignDataWrapper));
+   fdw = palloc_object(ForeignDataWrapper);
    fdw->fdwid = fdwid;
    fdw->owner = fdwform->fdwowner;
    fdw->fdwname = pstrdup(NameStr(fdwform->fdwname));
@@ -140,7 +140,7 @@ GetForeignServerExtended(Oid serverid, bits16 flags)
 
    serverform = (Form_pg_foreign_server) GETSTRUCT(tp);
 
-   server = (ForeignServer *) palloc(sizeof(ForeignServer));
+   server = palloc_object(ForeignServer);
    server->serverid = serverid;
    server->servername = pstrdup(NameStr(serverform->srvname));
    server->owner = serverform->srvowner;
@@ -227,7 +227,7 @@ GetUserMapping(Oid userid, Oid serverid)
                        MappingUserName(userid), server->servername)));
    }
 
-   um = (UserMapping *) palloc(sizeof(UserMapping));
+   um = palloc_object(UserMapping);
    um->umid = ((Form_pg_user_mapping) GETSTRUCT(tp))->oid;
    um->userid = userid;
    um->serverid = serverid;
@@ -265,7 +265,7 @@ GetForeignTable(Oid relid)
        elog(ERROR, "cache lookup failed for foreign table %u", relid);
    tableform = (Form_pg_foreign_table) GETSTRUCT(tp);
 
-   ft = (ForeignTable *) palloc(sizeof(ForeignTable));
+   ft = palloc_object(ForeignTable);
    ft->relid = relid;
    ft->serverid = tableform->ftserver;
 
@@ -463,7 +463,7 @@ GetFdwRoutineForRelation(Relation relation, bool makecopy)
    /* We have valid cached data --- does the caller want a copy? */
    if (makecopy)
    {
-       fdwroutine = (FdwRoutine *) palloc(sizeof(FdwRoutine));
+       fdwroutine = palloc_object(FdwRoutine);
        memcpy(fdwroutine, relation->rd_fdwroutine, sizeof(FdwRoutine));
        return fdwroutine;
    }
index e978b996baede96af367bd67958cd9a8f659d346..15c3475ede2f9d34cb9dae63f7e18218f4120732 100644 (file)
@@ -500,7 +500,7 @@ llvm_copy_attributes_at_index(LLVMValueRef v_from, LLVMValueRef v_to, uint32 ind
    if (num_attributes == 0)
        return;
 
-   attrs = palloc(sizeof(LLVMAttributeRef) * num_attributes);
+   attrs = palloc_array(LLVMAttributeRef, num_attributes);
    LLVMGetAttributesAtIndex(v_from, index, attrs);
 
    for (int attno = 0; attno < num_attributes; attno++)
@@ -1123,9 +1123,9 @@ llvm_resolve_symbols(LLVMOrcDefinitionGeneratorRef GeneratorObj, void *Ctx,
                     LLVMOrcCLookupSet LookupSet, size_t LookupSetSize)
 {
 #if LLVM_VERSION_MAJOR > 14
-   LLVMOrcCSymbolMapPairs symbols = palloc0(sizeof(LLVMOrcCSymbolMapPair) * LookupSetSize);
+   LLVMOrcCSymbolMapPairs symbols = palloc0_array(LLVMOrcCSymbolMapPair, LookupSetSize);
 #else
-   LLVMOrcCSymbolMapPairs symbols = palloc0(sizeof(LLVMJITCSymbolMapPair) * LookupSetSize);
+   LLVMOrcCSymbolMapPairs symbols = palloc0_array(LLVMJITCSymbolMapPair, LookupSetSize);
 #endif
    LLVMErrorRef error;
    LLVMOrcMaterializationUnitRef mu;
index f500cbda893ef20f2c0b67558d7d66786c0f4a3f..89167d15c3fb5a7951182e101a5e9316cd8c4507 100644 (file)
@@ -156,12 +156,12 @@ slot_compile_deform(LLVMJitContext *context, TupleDesc desc,
 
    b = LLVMCreateBuilderInContext(lc);
 
-   attcheckattnoblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
-   attstartblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
-   attisnullblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
-   attcheckalignblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
-   attalignblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
-   attstoreblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
+   attcheckattnoblocks = palloc_array(LLVMBasicBlockRef, natts);
+   attstartblocks = palloc_array(LLVMBasicBlockRef, natts);
+   attisnullblocks = palloc_array(LLVMBasicBlockRef, natts);
+   attcheckalignblocks = palloc_array(LLVMBasicBlockRef, natts);
+   attalignblocks = palloc_array(LLVMBasicBlockRef, natts);
+   attstoreblocks = palloc_array(LLVMBasicBlockRef, natts);
 
    known_alignment = 0;
 
index ac88881e995ec48264db8c30d8d2adb03810f456..33e62f980bd2afde2053278529aec31a9a858300 100644 (file)
@@ -297,7 +297,7 @@ llvm_compile_expr(ExprState *state)
                                   "v.econtext.aggnulls");
 
    /* allocate blocks for each op upfront, so we can do jumps easily */
-   opblocks = palloc(sizeof(LLVMBasicBlockRef) * state->steps_len);
+   opblocks = palloc_array(LLVMBasicBlockRef, state->steps_len);
    for (int opno = 0; opno < state->steps_len; opno++)
        opblocks[opno] = l_bb_append_v(eval_fn, "b.op.%d.start", opno);
 
@@ -2505,7 +2505,7 @@ llvm_compile_expr(ExprState *state)
                    v_nullsp = l_ptr_const(nulls, l_ptr(TypeStorageBool));
 
                    /* create blocks for checking args */
-                   b_checknulls = palloc(sizeof(LLVMBasicBlockRef) * nargs);
+                   b_checknulls = palloc_array(LLVMBasicBlockRef, nargs);
                    for (int argno = 0; argno < nargs; argno++)
                    {
                        b_checknulls[argno] =
@@ -2956,7 +2956,7 @@ llvm_compile_expr(ExprState *state)
     */
    {
 
-       CompiledExprState *cstate = palloc0(sizeof(CompiledExprState));
+       CompiledExprState *cstate = palloc0_object(CompiledExprState);
 
        cstate->context = context;
        cstate->funcname = funcname;
@@ -3068,7 +3068,7 @@ build_EvalXFuncInt(LLVMBuilderRef b, LLVMModuleRef mod, const char *funcname,
        elog(ERROR, "parameter mismatch: %s expects %d passed %d",
             funcname, LLVMCountParams(v_fn), nargs + 2);
 
-   params = palloc(sizeof(LLVMValueRef) * (2 + nargs));
+   params = palloc_array(LLVMValueRef, (2 + nargs));
 
    params[argno++] = v_state;
    params[argno++] = l_ptr_const(op, l_ptr(StructExprEvalStep));
index 5af789652c79465541dd1daf37966cf4cc039d73..ed54f190494b4dd1f4a6f9bfb0415f9ec9e30654 100644 (file)
@@ -38,7 +38,7 @@ static bool hk_depth_search(BipartiteMatchState *state, int u);
 BipartiteMatchState *
 BipartiteMatch(int u_size, int v_size, short **adjacency)
 {
-   BipartiteMatchState *state = palloc(sizeof(BipartiteMatchState));
+   BipartiteMatchState *state = palloc_object(BipartiteMatchState);
 
    if (u_size < 0 || u_size >= SHRT_MAX ||
        v_size < 0 || v_size >= SHRT_MAX)
index e1ba367cf17bf4f69be57e5e5f9f6756815efe40..82f6aa966de97076e4ae6033027c4e4e41b88135 100644 (file)
@@ -211,7 +211,7 @@ dshash_create(dsa_area *area, const dshash_parameters *params, void *arg)
    dsa_pointer control;
 
    /* Allocate the backend-local object representing the hash table. */
-   hash_table = palloc(sizeof(dshash_table));
+   hash_table = palloc_object(dshash_table);
 
    /* Allocate the control object in shared memory. */
    control = dsa_allocate(area, sizeof(dshash_table_control));
@@ -276,7 +276,7 @@ dshash_attach(dsa_area *area, const dshash_parameters *params,
    dsa_pointer control;
 
    /* Allocate the backend-local object representing the hash table. */
-   hash_table = palloc(sizeof(dshash_table));
+   hash_table = palloc_object(dshash_table);
 
    /* Find the control object in shared memory. */
    control = handle;
index f4153b0e15a24da8d0cb65b8a405aee5b80210bb..aca1df2ad5a1f8772a9ee0a8ef918d0d984c0a85 100644 (file)
@@ -284,7 +284,7 @@ intset_create(void)
 {
    IntegerSet *intset;
 
-   intset = (IntegerSet *) palloc(sizeof(IntegerSet));
+   intset = palloc_object(IntegerSet);
    intset->context = CurrentMemoryContext;
    intset->mem_used = GetMemoryChunkSpace(intset);
 
index fa8431f794639df76f87255b56b3552f8e25a688..3497dc7902afad76c01efaa69a0c681b4e614dc2 100644 (file)
@@ -43,7 +43,7 @@ pairingheap_allocate(pairingheap_comparator compare, void *arg)
 {
    pairingheap *heap;
 
-   heap = (pairingheap *) palloc(sizeof(pairingheap));
+   heap = palloc_object(pairingheap);
    pairingheap_initialize(heap, compare, arg);
 
    return heap;
index 1f0553f914d47f162abee5c01f3060f47799ed88..8fe6bfc539a21f27b4f16a9dd792aceb7a97fa2d 100644 (file)
@@ -106,7 +106,7 @@ rbt_create(Size node_size,
           rbt_freefunc freefunc,
           void *arg)
 {
-   RBTree     *tree = (RBTree *) palloc(sizeof(RBTree));
+   RBTree     *tree = palloc_object(RBTree);
 
    Assert(node_size > sizeof(RBTNode));
 
index 27f7af7be0024db9cbd7449ed5af89cc474af496..32a370ede117b98018aa80174266da3167a9c1ba 100644 (file)
@@ -108,7 +108,7 @@ oauth_init(Port *port, const char *selected_mech, const char *shadow_pass)
                errcode(ERRCODE_PROTOCOL_VIOLATION),
                errmsg("client selected an invalid SASL authentication mechanism"));
 
-   ctx = palloc0(sizeof(*ctx));
+   ctx = palloc0_object(struct oauth_ctx);
 
    ctx->state = OAUTH_STATE_INIT;
    ctx->port = port;
@@ -656,7 +656,7 @@ validate(Port *port, const char *auth)
                errmsg("validation of OAuth token requested without a validator loaded"));
 
    /* Call the validation function from the validator module */
-   ret = palloc0(sizeof(ValidatorModuleResult));
+   ret = palloc0_object(ValidatorModuleResult);
    if (!ValidatorCallbacks->validate_cb(validator_module_state, token,
                                         port->user_name, ret))
    {
@@ -785,14 +785,14 @@ load_validator_library(const char *libname)
                       "OAuth validator", libname, "validate_cb"));
 
    /* Allocate memory for validator library private state data */
-   validator_module_state = (ValidatorModuleState *) palloc0(sizeof(ValidatorModuleState));
+   validator_module_state = palloc0_object(ValidatorModuleState);
    validator_module_state->sversion = PG_VERSION_NUM;
 
    if (ValidatorCallbacks->startup_cb != NULL)
        ValidatorCallbacks->startup_cb(validator_module_state);
 
    /* Shut down the library before cleaning up its state. */
-   mcb = palloc0(sizeof(*mcb));
+   mcb = palloc0_object(MemoryContextCallback);
    mcb->func = shutdown_validator_library;
 
    MemoryContextRegisterResetCallback(CurrentMemoryContext, mcb);
index e343ffea46f421575264cf05ece2c7d715560249..2d6d97b4bb6eea75797c4206ea301c392f507f96 100644 (file)
@@ -240,7 +240,7 @@ scram_init(Port *port, const char *selected_mech, const char *shadow_pass)
    scram_state *state;
    bool        got_secret;
 
-   state = (scram_state *) palloc0(sizeof(scram_state));
+   state = palloc0_object(scram_state);
    state->port = port;
    state->state = SCRAM_AUTH_INIT;
 
index 6cb25399c26ed85321b7a27c54f58f9b3fa20585..4c259f58d77b01a9c6e46e5c78b8608890c0f747 100644 (file)
@@ -309,7 +309,7 @@ regcomp_auth_token(AuthToken *token, char *filename, int line_num,
    if (token->string[0] != '/')
        return 0;               /* nothing to compile */
 
-   token->regex = (regex_t *) palloc0(sizeof(regex_t));
+   token->regex = palloc0_object(regex_t);
    wstr = palloc((strlen(token->string + 1) + 1) * sizeof(pg_wchar));
    wlen = pg_mb2wchar_with_len(token->string + 1,
                                wstr, strlen(token->string + 1));
@@ -891,7 +891,7 @@ process_line:
         * to this list.
         */
        oldcxt = MemoryContextSwitchTo(tokenize_context);
-       tok_line = (TokenizedAuthLine *) palloc0(sizeof(TokenizedAuthLine));
+       tok_line = palloc0_object(TokenizedAuthLine);
        tok_line->fields = current_line;
        tok_line->file_name = pstrdup(filename);
        tok_line->line_num = line_number;
@@ -1339,7 +1339,7 @@ parse_hba_line(TokenizedAuthLine *tok_line, int elevel)
    AuthToken  *token;
    HbaLine    *parsedline;
 
-   parsedline = palloc0(sizeof(HbaLine));
+   parsedline = palloc0_object(HbaLine);
    parsedline->sourcefile = pstrdup(file_name);
    parsedline->linenumber = line_num;
    parsedline->rawline = pstrdup(tok_line->raw_line);
@@ -2622,7 +2622,7 @@ check_hba(Port *port)
    }
 
    /* If no matching entry was found, then implicitly reject. */
-   hba = palloc0(sizeof(HbaLine));
+   hba = palloc0_object(HbaLine);
    hba->auth_method = uaImplicitReject;
    port->hba = hba;
 }
@@ -2758,7 +2758,7 @@ parse_ident_line(TokenizedAuthLine *tok_line, int elevel)
    Assert(tok_line->fields != NIL);
    field = list_head(tok_line->fields);
 
-   parsedline = palloc0(sizeof(IdentLine));
+   parsedline = palloc0_object(IdentLine);
    parsedline->linenumber = line_num;
 
    /* Get the map token (must exist) */
index 40b180644eb8a52e70e81f6d20d848c1a835daad..e33623fdbace73e726bb15d21e92221e8b3a69c0 100644 (file)
@@ -178,7 +178,7 @@ pq_init(ClientSocket *client_sock)
    int         latch_pos PG_USED_FOR_ASSERTS_ONLY;
 
    /* allocate the Port struct and copy the ClientSocket contents to it */
-   port = palloc0(sizeof(Port));
+   port = palloc0_object(Port);
    port->sock = client_sock->sock;
    memcpy(&port->raddr.addr, &client_sock->raddr.addr, client_sock->raddr.salen);
    port->raddr.salen = client_sock->raddr.salen;
index d228318dc72efa515422b55cd55898c39d52f0eb..024a2b2fd841617313ddbecadf199ee5b251889d 100644 (file)
@@ -2953,7 +2953,7 @@ expression_tree_mutator_impl(Node *node,
     */
 
 #define FLATCOPY(newnode, node, nodetype)  \
-   ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
+   ( (newnode) = palloc_object(nodetype), \
      memcpy((newnode), (node), sizeof(nodetype)) )
 
 #define MUTATE(newfield, oldfield, fieldtype)  \
index 31f971519772d5266e8bb51937b3c66d4bff6cc4..ffc230af4278c0008691a1bde974e69ca3e7edb5 100644 (file)
@@ -181,7 +181,7 @@ InitJumble(void)
 {
    JumbleState *jstate;
 
-   jstate = (JumbleState *) palloc(sizeof(JumbleState));
+   jstate = palloc_object(JumbleState);
 
    /* Set up workspace for query jumbling */
    jstate->jumble = (unsigned char *) palloc(JUMBLE_SIZE);
index 1f83d0d55f5283ef3752994e83db23519e6830d3..a2fa96317dbb70b95b7509944aa3a9f9608ef220 100644 (file)
@@ -683,7 +683,7 @@ tbm_begin_private_iterate(TIDBitmap *tbm)
     * Create the TBMPrivateIterator struct, with enough trailing space to
     * serve the needs of the TBMIterateResult sub-struct.
     */
-   iterator = (TBMPrivateIterator *) palloc(sizeof(TBMPrivateIterator));
+   iterator = palloc_object(TBMPrivateIterator);
    iterator->tbm = tbm;
 
    /*
@@ -1468,7 +1468,7 @@ tbm_attach_shared_iterate(dsa_area *dsa, dsa_pointer dp)
     * Create the TBMSharedIterator struct, with enough trailing space to
     * serve the needs of the TBMIterateResult sub-struct.
     */
-   iterator = (TBMSharedIterator *) palloc0(sizeof(TBMSharedIterator));
+   iterator = palloc0_object(TBMSharedIterator);
 
    istate = (TBMSharedIteratorState *) dsa_get_address(dsa, dp);
 
index af289f7eeb7131fb3b8a602498a56a17673cc820..f11a59e4a289ea3a118b81c0aeab52da06947183 100644 (file)
@@ -62,7 +62,7 @@ alloc_edge_table(PlannerInfo *root, int num_gene)
     * directly; 0 will not be used
     */
 
-   edge_table = (Edge *) palloc((num_gene + 1) * sizeof(Edge));
+   edge_table = palloc_array(Edge, num_gene + 1);
 
    return edge_table;
 }
index 8005754c8c633f293f59a62ca2a005aaac5bdd1f..c65a31d0679d6dc508df9eff68f3f4c77b66fbd6 100644 (file)
@@ -191,7 +191,7 @@ gimme_tree(PlannerInfo *root, Gene *tour, int num_gene)
                                          cur_rel_index - 1);
 
        /* Make it into a single-rel clump */
-       cur_clump = (Clump *) palloc(sizeof(Clump));
+       cur_clump = palloc_object(Clump);
        cur_clump->joinrel = cur_rel;
        cur_clump->size = 1;
 
index 01d55711925431d53112369aa11a981cb36ebf56..af1cb868391544ae1d7839711398e7a4252aad30 100644 (file)
 void
 pmx(PlannerInfo *root, Gene *tour1, Gene *tour2, Gene *offspring, int num_gene)
 {
-   int        *failed = (int *) palloc((num_gene + 1) * sizeof(int));
-   int        *from = (int *) palloc((num_gene + 1) * sizeof(int));
-   int        *indx = (int *) palloc((num_gene + 1) * sizeof(int));
-   int        *check_list = (int *) palloc((num_gene + 1) * sizeof(int));
+   int        *failed = palloc_array(int, num_gene + 1);
+   int        *from = palloc_array(int, num_gene + 1);
+   int        *indx = palloc_array(int, num_gene + 1);
+   int        *check_list = palloc_array(int, num_gene + 1);
 
    int         left,
                right,
index 89e3d6a027739db793aa44eff350a94f4a360ac6..d0f53d888ef43ad0299896aa38c15a7932e27038 100644 (file)
@@ -46,17 +46,17 @@ alloc_pool(PlannerInfo *root, int pool_size, int string_length)
    int         i;
 
    /* pool */
-   new_pool = (Pool *) palloc(sizeof(Pool));
+   new_pool = palloc_object(Pool);
    new_pool->size = pool_size;
    new_pool->string_length = string_length;
 
    /* all chromosome */
-   new_pool->data = (Chromosome *) palloc(pool_size * sizeof(Chromosome));
+   new_pool->data = palloc_array(Chromosome, pool_size);
 
    /* all gene */
    chromo = (Chromosome *) new_pool->data; /* vector of all chromos */
    for (i = 0; i < pool_size; i++)
-       chromo[i].string = palloc((string_length + 1) * sizeof(Gene));
+       chromo[i].string = palloc_array(Gene, string_length + 1);
 
    return new_pool;
 }
@@ -163,8 +163,8 @@ alloc_chromo(PlannerInfo *root, int string_length)
 {
    Chromosome *chromo;
 
-   chromo = (Chromosome *) palloc(sizeof(Chromosome));
-   chromo->string = (Gene *) palloc((string_length + 1) * sizeof(Gene));
+   chromo = palloc_object(Chromosome);
+   chromo->string = palloc_array(Gene, string_length + 1);
 
    return chromo;
 }
index a5d3e47ad115ecc2fa07f220db39fbff0a0e2bde..41d35c179e14edfaa163fb546e8521835a2df278 100644 (file)
@@ -74,7 +74,7 @@ alloc_city_table(PlannerInfo *root, int num_gene)
     * palloc one extra location so that nodes numbered 1..n can be indexed
     * directly; 0 will not be used
     */
-   city_table = (City *) palloc((num_gene + 1) * sizeof(City));
+   city_table = palloc_array(City, num_gene + 1);
 
    return city_table;
 }
index d0f516b76454c473d29ddb12c737a9f98f4b69d5..eb9b7f3eabd02bb74636d56997c09a1b9dc07f33 100644 (file)
@@ -495,7 +495,7 @@ addRangeClause(RangeQueryClause **rqlist, Node *clause,
    }
 
    /* No matching var found, so make a new clause-pair data structure */
-   rqelem = (RangeQueryClause *) palloc(sizeof(RangeQueryClause));
+   rqelem = palloc_object(RangeQueryClause);
    rqelem->var = var;
    if (is_lobound)
    {
index 5a7283bd2f535572e0faa93db44514618b768b00..a39cc793b4d824ca3f95b510ae00521cdcc2a731 100644 (file)
@@ -2179,7 +2179,7 @@ append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
     * whichever is less.
     */
    arrlen = Min(parallel_workers, numpaths);
-   costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
+   costarr = palloc_array(Cost, arrlen);
 
    /* The first few paths will each be claimed by a different worker. */
    path_index = 0;
@@ -4137,7 +4137,7 @@ cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
    /* Cache the result in suitably long-lived workspace */
    oldcontext = MemoryContextSwitchTo(root->planner_cxt);
 
-   cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
+   cache = palloc_object(MergeScanSelCache);
    cache->opfamily = pathkey->pk_opfamily;
    cache->collation = pathkey->pk_eclass->ec_collation;
    cache->cmptype = pathkey->pk_cmptype;
index 2654c59c4c6046ff9f95b1985b28115f63ab9172..5d4f81ee77e0749a8414cddfad43024435b31ad1 100644 (file)
@@ -1291,7 +1291,7 @@ group_similar_or_args(PlannerInfo *root, RelOptInfo *rel, RestrictInfo *rinfo)
     * which will be used to sort these arguments at the next step.
     */
    i = -1;
-   matches = (OrArgIndexMatch *) palloc(sizeof(OrArgIndexMatch) * n);
+   matches = palloc_array(OrArgIndexMatch, n);
    foreach(lc, orargs)
    {
        Node       *arg = lfirst(lc);
@@ -1853,8 +1853,7 @@ choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
     * same set of clauses; keep only the cheapest-to-scan of any such groups.
     * The surviving paths are put into an array for qsort'ing.
     */
-   pathinfoarray = (PathClauseUsage **)
-       palloc(npaths * sizeof(PathClauseUsage *));
+   pathinfoarray = palloc_array(PathClauseUsage *, npaths);
    clauselist = NIL;
    npaths = 0;
    foreach(l, paths)
@@ -2090,7 +2089,7 @@ classify_index_clause_usage(Path *path, List **clauselist)
    Bitmapset  *clauseids;
    ListCell   *lc;
 
-   result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
+   result = palloc_object(PathClauseUsage);
    result->path = path;
 
    /* Recursively find the quals and preds used by the path */
index 5d1fc3899dae10fcdc92c21c5bde65c3a5a362a4..8827b9a5245a02d21528bdd1fc351f856a469797 100644 (file)
@@ -1990,8 +1990,7 @@ compute_partition_bounds(PlannerInfo *root, RelOptInfo *rel1,
        Assert(nparts > 0);
        joinrel->boundinfo = boundinfo;
        joinrel->nparts = nparts;
-       joinrel->part_rels =
-           (RelOptInfo **) palloc0(sizeof(RelOptInfo *) * nparts);
+       joinrel->part_rels = palloc0_array(RelOptInfo *, nparts);
    }
    else
    {
index 296a894b8578fc347db29a40880a4598cd0049aa..e2784c01549c02e10daba28f00e3893ca81b1241 100644 (file)
@@ -2363,8 +2363,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove)
     * In order to find relations with the same oid we first build an array of
     * candidates and then sort it by oid.
     */
-   candidates = (SelfJoinCandidate *) palloc(sizeof(SelfJoinCandidate) *
-                                             numRels);
+   candidates = palloc_array(SelfJoinCandidate, numRels);
    i = -1;
    j = 0;
    while ((i = bms_next_member(relids, i)) >= 0)
index 8af091ba6471b8709aefffe01f321c79ce4726de..bc417f9384018cb4a3c87fd121b1428995bdec22 100644 (file)
@@ -2207,7 +2207,7 @@ remap_groupColIdx(PlannerInfo *root, List *groupClause)
 
    Assert(grouping_map);
 
-   new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
+   new_grpColIdx = palloc0_array(AttrNumber, list_length(groupClause));
 
    i = 0;
    foreach(lc, groupClause)
@@ -2496,9 +2496,9 @@ create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
     * Convert SortGroupClause lists into arrays of attr indexes and equality
     * operators, as wanted by executor.
     */
-   partColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numPart);
-   partOperators = (Oid *) palloc(sizeof(Oid) * numPart);
-   partCollations = (Oid *) palloc(sizeof(Oid) * numPart);
+   partColIdx = palloc_array(AttrNumber, numPart);
+   partOperators = palloc_array(Oid, numPart);
+   partCollations = palloc_array(Oid, numPart);
 
    partNumCols = 0;
    foreach(lc, wc->partitionClause)
@@ -2513,9 +2513,9 @@ create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
        partNumCols++;
    }
 
-   ordColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numOrder);
-   ordOperators = (Oid *) palloc(sizeof(Oid) * numOrder);
-   ordCollations = (Oid *) palloc(sizeof(Oid) * numOrder);
+   ordColIdx = palloc_array(AttrNumber, numOrder);
+   ordOperators = palloc_array(Oid, numOrder);
+   ordCollations = palloc_array(Oid, numOrder);
 
    ordNumCols = 0;
    foreach(lc, wc->orderClause)
@@ -5862,9 +5862,9 @@ make_recursive_union(List *tlist,
        Oid        *dupCollations;
        ListCell   *slitem;
 
-       dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
-       dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
-       dupCollations = (Oid *) palloc(sizeof(Oid) * numCols);
+       dupColIdx = palloc_array(AttrNumber, numCols);
+       dupOperators = palloc_array(Oid, numCols);
+       dupCollations = palloc_array(Oid, numCols);
 
        foreach(slitem, distinctList)
        {
@@ -6694,9 +6694,9 @@ make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols,
     * prepare_sort_from_pathkeys ... maybe unify sometime?
     */
    Assert(numCols >= 0 && numCols <= list_length(pathkeys));
-   uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
-   uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
-   uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
+   uniqColIdx = palloc_array(AttrNumber, numCols);
+   uniqOperators = palloc_array(Oid, numCols);
+   uniqCollations = palloc_array(Oid, numCols);
 
    foreach(lc, pathkeys)
    {
@@ -6831,10 +6831,10 @@ make_setop(SetOpCmd cmd, SetOpStrategy strategy,
     * convert SortGroupClause list into arrays of attr indexes and comparison
     * operators, as wanted by executor
     */
-   cmpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
-   cmpOperators = (Oid *) palloc(sizeof(Oid) * numCols);
-   cmpCollations = (Oid *) palloc(sizeof(Oid) * numCols);
-   cmpNullsFirst = (bool *) palloc(sizeof(bool) * numCols);
+   cmpColIdx = palloc_array(AttrNumber, numCols);
+   cmpOperators = palloc_array(Oid, numCols);
+   cmpCollations = palloc_array(Oid, numCols);
+   cmpNullsFirst = palloc_array(bool, numCols);
 
    foreach(slitem, groupList)
    {
index 671c5cde8fc172a83c36382d777c3540b50a4d13..f7f76469a2dbf5d3dc36bf3d7768ef778ed5e7c3 100644 (file)
@@ -438,8 +438,7 @@ remove_useless_groupby_columns(PlannerInfo *root)
     * Fill groupbyattnos[k] with a bitmapset of the column attnos of RTE k
     * that are GROUP BY items.
     */
-   groupbyattnos = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
-                                          (list_length(parse->rtable) + 1));
+   groupbyattnos = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
    foreach(lc, root->processed_groupClause)
    {
        SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
@@ -597,8 +596,7 @@ remove_useless_groupby_columns(PlannerInfo *root)
             * allocate the surplusvars[] array until we find something.
             */
            if (surplusvars == NULL)
-               surplusvars = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
-                                                    (list_length(parse->rtable) + 1));
+               surplusvars = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
 
            /* Remember the attnos of the removable columns */
            surplusvars[relid] = bms_difference(relattnos, best_keycolumns);
index a2ac58d246ee1af819d385e31732179ca10d502e..1a35c269e04acb3b2b7fc46fd2471a4083ccabe7 100644 (file)
@@ -336,7 +336,7 @@ build_minmax_path(PlannerInfo *root, MinMaxAggInfo *mminfo,
     * than before.  (This means that when we are done, there will be no Vars
     * of level 1, which is why the subquery can become an initplan.)
     */
-   subroot = (PlannerInfo *) palloc(sizeof(PlannerInfo));
+   subroot = palloc_object(PlannerInfo);
    memcpy(subroot, root, sizeof(PlannerInfo));
    subroot->query_level++;
    subroot->parent_root = root;
index fd77334e5fd46c9d4381e8a249edc21c3ac6fb65..8b22c30559b26d7a744bd3bfd75ba47663daa688 100644 (file)
@@ -2213,7 +2213,7 @@ preprocess_grouping_sets(PlannerInfo *root)
    List       *sets;
    int         maxref = 0;
    ListCell   *lc_set;
-   grouping_sets_data *gd = palloc0(sizeof(grouping_sets_data));
+   grouping_sets_data *gd = palloc0_object(grouping_sets_data);
 
    /*
     * We don't currently make any attempt to optimize the groupClause when
@@ -5977,8 +5977,8 @@ select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
    List       *result = NIL;
    ListCell   *lc;
    int         nActive = 0;
-   WindowClauseSortData *actives = palloc(sizeof(WindowClauseSortData)
-                                          * list_length(windowClause));
+   WindowClauseSortData *actives = palloc_array(WindowClauseSortData,
+                                                list_length(windowClause));
 
    /* First, construct an array of the active windows */
    foreach(lc, windowClause)
index ccdc9bc264ab93ed4fc06b6c853362c584d89d42..cd7ea1e6b587354c0384e859786853ccf5be1450 100644 (file)
@@ -312,7 +312,7 @@ set_plan_references(PlannerInfo *root, Plan *plan)
               root->simple_rte_array[rc->rti] != NULL);
 
        /* flat copy is enough since all fields are scalars */
-       newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
+       newrc = palloc_object(PlanRowMark);
        memcpy(newrc, rc, sizeof(PlanRowMark));
 
        /* adjust indexes ... but *not* the rowmarkId */
@@ -545,7 +545,7 @@ add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
    RangeTblEntry *newrte;
 
    /* flat copy to duplicate all the scalar fields */
-   newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
+   newrte = palloc_object(RangeTblEntry);
    memcpy(newrte, rte, sizeof(RangeTblEntry));
 
    /* zap unneeded sub-structure */
@@ -2028,7 +2028,7 @@ offset_relid_set(Relids relids, int rtoffset)
 static inline Var *
 copyVar(Var *var)
 {
-   Var        *newvar = (Var *) palloc(sizeof(Var));
+   Var        *newvar = palloc_object(Var);
 
    *newvar = *var;
    return newvar;
index 7581695647daa98e63b2f32b86a49fc0eb40d9c6..c3b726e93e7d3364d3d7799db25d9645ff1b9d51 100644 (file)
@@ -741,7 +741,7 @@ pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
         * Make a modifiable copy of join node, but don't bother copying its
         * subnodes (yet).
         */
-       j = (JoinExpr *) palloc(sizeof(JoinExpr));
+       j = palloc_object(JoinExpr);
        memcpy(j, jtnode, sizeof(JoinExpr));
        jtlink = (Node *) j;
 
@@ -3240,8 +3240,7 @@ reduce_outer_joins_pass1(Node *jtnode)
 {
    reduce_outer_joins_pass1_state *result;
 
-   result = (reduce_outer_joins_pass1_state *)
-       palloc(sizeof(reduce_outer_joins_pass1_state));
+   result = palloc_object(reduce_outer_joins_pass1_state);
    result->relids = NULL;
    result->contains_outer = false;
    result->sub_states = NIL;
@@ -3593,7 +3592,7 @@ report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
 {
    reduce_outer_joins_partial_state *statep;
 
-   statep = palloc(sizeof(reduce_outer_joins_partial_state));
+   statep = palloc_object(reduce_outer_joins_partial_state);
    statep->full_join_rti = rtindex;
    statep->unreduced_side = relids;
    state2->partial_reduced = lappend(state2->partial_reduced, statep);
index f528f096a5688ad0d00c62ee9e26cba1e5df2e66..a01b02f3a7b6ffcc6945106714086237db739aa4 100644 (file)
@@ -1629,7 +1629,7 @@ generate_append_tlist(List *colTypes, List *colCollations,
     * If the inputs all agree on type and typmod of a particular column, use
     * that typmod; else use -1.
     */
-   colTypmods = (int32 *) palloc(list_length(colTypes) * sizeof(int32));
+   colTypmods = palloc_array(int32, list_length(colTypes));
 
    foreach(tlistl, input_tlists)
    {
index 69b8b0c2ae05685d1a45dc694ee7735e45b9ee3f..271bb4e68282675484b5465af24040957718af49 100644 (file)
@@ -808,8 +808,7 @@ find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
    int         i;
 
    /* Allocate an array that's certainly big enough */
-   appinfos = (AppendRelInfo **)
-       palloc(sizeof(AppendRelInfo *) * bms_num_members(relids));
+   appinfos = palloc_array(AppendRelInfo *, bms_num_members(relids));
 
    i = -1;
    while ((i = bms_next_member(relids, i)) >= 0)
index bda4c4eb29226805f95a128d19568aa21cead931..ddafc21c819a948f391461f7b586a06431327a59 100644 (file)
@@ -239,7 +239,7 @@ contain_window_function(Node *clause)
 WindowFuncLists *
 find_window_functions(Node *clause, Index maxWinRef)
 {
-   WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
+   WindowFuncLists *lists = palloc_object(WindowFuncLists);
 
    lists->numWindowFuncs = 0;
    lists->maxWinRef = maxWinRef;
@@ -5744,8 +5744,8 @@ make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid,
 
        get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
 
-       elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
-       nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
+       elems = palloc_array(Datum, list_length(exprs));
+       nulls = palloc_array(bool, list_length(exprs));
        foreach_node(Const, value, exprs)
        {
            elems[i] = value->constvalue;
index 03d32277ba1eeaf4bec70dbc686f66c1b9c80451..2bc4ad32631aad177ab76f110397c3c3672b6b39 100644 (file)
@@ -98,10 +98,8 @@ SetPlannerGlobalExtensionState(PlannerGlobal *glob, int extension_id,
        int         i;
 
        i = pg_nextpower2_32(extension_id + 1);
-       glob->extension_state = (void **)
-           repalloc0(glob->extension_state,
-                     glob->extension_state_allocated * sizeof(void *),
-                     i * sizeof(void *));
+       glob->extension_state = repalloc0_array(glob->extension_state, void *,
+                                               glob->extension_state_allocated, i);
        glob->extension_state_allocated = i;
    }
 
@@ -134,10 +132,8 @@ SetPlannerInfoExtensionState(PlannerInfo *root, int extension_id,
        int         i;
 
        i = pg_nextpower2_32(extension_id + 1);
-       root->extension_state = (void **)
-           repalloc0(root->extension_state,
-                     root->extension_state_allocated * sizeof(void *),
-                     i * sizeof(void *));
+       root->extension_state = repalloc0_array(root->extension_state, void *,
+                                               root->extension_state_allocated, i);
        root->extension_state_allocated = i;
    }
 
@@ -172,10 +168,8 @@ SetRelOptInfoExtensionState(RelOptInfo *rel, int extension_id,
        int         i;
 
        i = pg_nextpower2_32(extension_id + 1);
-       rel->extension_state = (void **)
-           repalloc0(rel->extension_state,
-                     rel->extension_state_allocated * sizeof(void *),
-                     i * sizeof(void *));
+       rel->extension_state = repalloc0_array(rel->extension_state, void *,
+                                              rel->extension_state_allocated, i);
        rel->extension_state_allocated = i;
    }
 
index ed0dac37f5153abec3d095cebd2841fd3e934d9b..e553afb7f01bcf1558b2770afd883ea37cdb4de2 100644 (file)
--- a/