简体   繁体   English

从字符串中读取大小后分配大小为'n'的缓冲区

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

I'm working on USB communication. 我正在研究USB通信。 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]. 来自主机的数据为“ 5”,这是一个字符串,我需要分配大小为5的缓冲区。例如:rec_buff [5]。 After reading the size from host. 从主机读取大小后。

Every time the size varies how can i do this with C code snippet. 每当大小变化时,我该如何使用C代码片段来完成此操作。 I have no idea how to do this. 我不知道该怎么做。 I used to work on java, i'm a newbie to C. 我曾经在Java上工作,我是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). 然后,您要查找的是内存池(固定块大小)或固定大小的数组(在.bss节中预先分配的一个)。

You could take a look at how an API for memory pool in Zephyr RTOS looks like and inspect source code for implementation details. 您可以查看Zephyr RTOS中用于内存池API的外观,并检查源代码以了解实现细节。 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. 例如,您可以实现某种状态机并以块为单位解析输入,或者只是中止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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