Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

realloc variants

Tags:

c

realloc

Just to situate the context: it's about a string pool, meaning a hash table with string keys (actually special strings that know their length, but I guess this detail is irrelevant here). The point is the resizing of the array of lists (used as table buckets) when the pool needs to grow. But --this is the core detail-- cells containing string actually in an array of cells, instead of being spread out in all corners of memory [1]. Thus, I don't need the lists anymore, they're just outdated stuff. So:

  1. Is there a variant of realloc that "zeroes" the memory area like calloc? I need that here because the items are not only pointers, but lists heads: the issue is to ensure an empty list is/shows as NULL. Else, is the best solution just to memset(p, size, 0);

  2. Is there a variant of realloc that does not copy if ever there is not enough space to grow on place, but instead just allocates like alloc? The issue here is that I don't need the data anymore, since strings need to be re-distributed in lists according to new modulo. Else, what is the best choice?

    • use realloc
    • (free &) use alloc
    • (free &) use calloc

Is this right in any case: realloc tries to alloc more space on place, else allocates elsewhere and silently copies? If yes, then maybe a problem is there are (at least) three use cases requiring different actions --in both cases where there is or there is not enough space on place-- but a single func with no option at all:

  • I need more place for these data and more to come (standard).
  • I need more place, but the data are garbage from now on.
  • I need more space and the area to be "zeroed".

What is the best option for me? What do you think else? Where can I find more reflexions or info on the topic?

Is there a reason why alloc has a different interface from calloc and realloc? (I mean specifying total-size vs single-size & count)

[1] The point was originally to make ordered sets & maps; for a string pool it is not needed but does not bother. Instead, it makes code clearer and provides locality of reference.

like image 918
denis 63 Avatar asked Apr 14 '26 19:04

denis 63


1 Answers

Is there a variant of realloc that "zeroes" the memory area like calloc?

No.

Is there a variant of realloc that does not copy if ever there is not enough space to grow on place, but instead just allocates like alloc?

No.

If I were you I'd probably use free and calloc. But ideally you want to design your system so that reallocations are infrequent and so the different performance characteristics of the various options are not significant. In other words, make sure that it doesn't matter which option you select.

like image 134
David Heffernan Avatar answered Apr 16 '26 08:04

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!