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)
@@