简体   繁体   中英

Allocate buffer of size 'n' after reading the size from a string

I'm working on USB communication. Here every time the size of data from the host varies. To avoid this from host it will send the size of data before sending the data so i need to allocate the buffer of size which host sends.

The data from host is "5" it is a string i need to allocate a buffer of size 5. ex: rec_buff[5]. After reading the size from host.

Every time the size varies how can i do this with C code snippet. I have no idea how to do this. I used to work on java, i'm a newbie to C.

I need to do it without using dynamic memory allocation.

Any help will be appreciated.Thanks in advance.

I assume you don't want memory allocation with variable size blocks because you don't want memory fragmentation. Then what you are looking for is a memory pool (fixed block sizes) or a fixed size array (one that is preallocated in .bss section).

You could take a look at how an API for memory pool in Zephyr RTOS looks like and inspect source code for implementation details. There is also question about implementing own memory pool .

An important aspect of this system will be handling what happens when input exceeds maximum available space in your buffers. You could eg implement some sort of state machine and parse input in chunks or simply abort.

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