-1

I need to create a vector of which I do not know the number of components at the moment of the declaration. For example, suppose that the vector will contain the prime numbers below a given n and I cannot know how many there are before actually evaluating them.

Whenever I allocate memory with malloc, I know that the memory can later be freed using free:

int main(int argc, char** argv)
{
    int* p=malloc(4*sizeof(int));
    for(int j=0; j<4; j++)
    {
        *(p+j)=2*j;
    }
    printf("%d %d %d %d\n", *p, *(p+1), *(p+2), *(p+3));
    free(p);
    return 0;
}

My idea was to allocate more memory than I what I need, and then to free only a portion of it. So, naively I would like to do something like int* p=malloc(1000*sizeof(int)) (supposing that I know for sure that p will have less than 1000 components) and then use free(p+j) where j is the number of meaningful components that I have given to p after the computation. But that is not allowed.

Of course, there is always the possibility of making a list instead, using struct, and create the array only at the end, but I don't like that solution, it seems convoluted to me.

What is the right way to create an array when I only know an upper bound for its size at the time of declaration, in case the size of the array will only be determined at the end?

3sm1r
  • 520
  • 4
  • 19
  • 5
    Does this answer your question? [dynamic memory allocation in c , free some part of memory that is allocated before using malloc()](https://stackoverflow.com/questions/23040343/dynamic-memory-allocation-in-c-free-some-part-of-memory-that-is-allocated-befo). `realloc` may be the option you are looking for. – Ted Lyngmo Jan 20 '23 at 19:50
  • 1
    Suppose you guessed `N` primes and did `int *p = malloc(N * sizeof *p)`. If you only use `M` of the elements, you can later do `p = realloc(p, M * sizeof *p);` – Weather Vane Jan 20 '23 at 19:51
  • 1
    If you want to reduce the size of a block of memory that was previously allocated with `malloc`, you can use `realloc`, giving it the new, smaller size. The initial portion is retained, but note that the address may change. – Tom Karzes Jan 20 '23 at 19:52

1 Answers1

5

Using free(p+j) is not valid because you can only pass to free a pointer that was returned by malloc, calloc, realloc or aligned_alloc.

And speaking of realloc, that's exactly what you would use to resize a piece of allocated memory:

void *t = realloc(p, j * sizeof *p);
if (t) p = t;

Note that you'll want to save the returned pointer in a separate variable in case realloc fails, in which case the original pointer is still valid.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
dbush
  • 205,898
  • 23
  • 218
  • 273