r/computerscience • u/ShadowGuyinRealLife • 11d ago
Discussion Any Way For Multiple Blocks of Memory to be Allocated In One Function?
In c malloc will allocate some memory that can store variables. It takes in the number of bytes needed to be allocated and it gives a pointer to where the memory is allocated. What happens is that in the heap, there is a bit of space for the data, and before and after that point in the heap there are some overhead bytes that are not used for data.
Is it possible to write a function that allocates multiple blocks that can be freed separately? For example, a function which takes parameters a and b where a is a size desired and b is a pointer to an integer. The function outputs a pointer p and writes a second value to b. It then allocates 3000 blocks of memory, each of which is size a and offset by the same ammount. So at address p, there is a block of size a, at p+ 1 b, there is a block of size a, at p + 2b there is a block of size a, at p + 3 b there is a block of size a, ... and at p = 2999b there is a block of size a. Each block can be accesses separately and deallocated separately.
Ok that's actually a really stupid way to do it. What would probably be more practical is something like a function which takes the inputs a and b with a being an integer (or long) which is how many bytes you want each block, b being a pointer to an array of long integers. Then use malloc (a) to get a block the size of a, write the pointer into the array b points to, malloc (a) to get another block, write in the next part of the array, malloc (a) to get another block of size a, write the pointer of that block into array b, and so on for 3000 times to get 3000 blocks of allocated memory. But I was wondering if there was a way to do it the first way even though that would not be very good and probably burn a lot more clock cycles than a practical way.

