简体   繁体   中英

Allocating block of memory then creating logical sub blocks of memory and returning pointers to those sub blocks

I got asked this question on an interview and I'm pretty confused after trying to google/search on SO:

"Write a C function that allocates 4K block of memory, then creates 10 logical sub-blocks and returns pointer to each of the sub-block"

I'm not entirely sure what "logical sub-block" means in the question. What's the best way to approach this?

Can I simply allocate a 4k block using malloc, and then creating additional pointers incremented by the 1/10 of the size (4k)? Is there some smart bit-manipulation tricks that make this easy?

Thanks in advance!

"Can I simply allocate a 4k block using malloc, and then creating additional pointers incremented by the 1/10 of the size (4k)? Is there some smart bit-manipulation tricks that make this easy?"

I think that it's not about bit-manipulation tricks, because dividing 4k by 10 is fairly easy.

What I'd be much more concerned about is the fact that malloc will give you a pointer that is suitably aligned for any data type (cf, for example, this online C standard draft ):

7.22.3 Memory management functions

(1) The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

Yet dividing such a memory block by 10 and picking out pointers to these chunks may likely give you pointers that are not properly aligned for the data types which you want to store then therein.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM