0

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.

  • 1
    Dynamic allocation in C is done via malloc (standard lib) / mmap (POSIX) & friends. – Michael Foukarakis Jan 03 '19 at 10:14
  • What is your question and what have you tried? – Andy J Jan 03 '19 at 10:27
  • Use `malloc`, as Michael says, but don't forget to `free` it when no longer needed. Before re-using the buffer you can call `realloc` to reallocate the buffer with a new size. – Paul Ogilvie Jan 03 '19 at 10:28
  • without malloc & realloc i need to do i'm working on embeded. – Nicolas_Tesla Jan 03 '19 at 10:32
  • Can you use variable length arrays? – GermanNerd Jan 03 '19 at 10:43
  • GermanNerd how to use it can you help me with a code snippet? – Nicolas_Tesla Jan 03 '19 at 10:51
  • 1
    Are you in an interrupt-handler? Do you run an RTOS with semaphores/events? Do the protocol units/messages have a maximum size? What flow-control is used to prevent exhaustion of the buffer space? We cannot help much with this unclear question given just 'cannot use malloc because embedded', and adding a lot more detail would make your Q. too broad.It is not possible to give a 'code snippet' for what is, essentially, a system design issue:( – Martin James Jan 03 '19 at 11:07
  • " host it will send the size of data" --> What is the largest size that will be sent? – chux - Reinstate Monica Jan 03 '19 at 15:25

1 Answers1

0

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 e.g. implement some sort of state machine and parse input in chunks or simply abort.

pbn
  • 2,406
  • 2
  • 26
  • 39