I’m trying to build a memory allocator in C. The user starts by saying how much memory he wants to use, and the smallest block size of memory that can be made available.
So, for example, let’s say the user requests 1024B with the smallest block size of 8B.
That means the possible block sizes would be 1024, 512, 256, 128, 64, 32, 16, and 8.
To keep track of the free blocks of memory, I have an array of pointers to structures. These structures are called Header, and the array is called FreeList.
What I mean is that FreeList[0] would contain a pointer to the space in memory where there is a block of memory size 8. FreeList[1] would contain a pointer to the space in memory where there is a block of memory size 16. etc.
typedef void * Addr;
struct Header
{
Addr next;
int order;
};
struct Header *FreeList[];
I’m trying to allocate memory for this free list to use with the following code:
FreeList = malloc(Order*sizeof(struct Header));
Where Order is the number of different block sizes you can have.
I’m getting the compile error ‘FreeList’ has an incomplete type.
I don’t want these pointers to point anywhere yet, I just want to allocate the space for the data.
In C language
is a tentative definition for a static array of unknown size (incomplete type). This array should be defined later with known compile-time size. The point is that it is a static array. It is not “allocatable” by
malloc.If you need an array of pointers that can be allocated at run-time by
malloc, you have to declare a pointer-to-pointer variablewhich is latter allocated with proper size
Note that in this case you are allocating an array of pointers, just like you wanted. And the
sizeofin the above allocation is equivalent tosizeof(struct Header *). i.e. size of a pointer (as opposed to the incorrectsizeof(struct Header)in your original code).This, again, allocates an array of uninitialized pointers. It is your responsibility to initialize these pointers, i.e. to make them point wherever you want them to point to. If necessary, you’ll have to allocate memory for the actual headers as well.
However, it is not really clear from what you posted whether you really need an array of pointers to headers or, maybe, an array of actual headers. Your explanation is confusing and, at times, self-contradictory. If you need an array of actual headers, then the pointer declaration and allocation will look as follows
In this case
sizeofexpression above is equivalent tosizeof(struct Header), as in our original example. Remember though that the allocated header array is still not initialized.