c - Manual allocation in a stringbuffer object -


For a small embedded application, I wrote some functions + struct that works as a string buffer (Similar to std) :: stringstream in C ++).

Works fine in this form of code, but there are some small issues:

  • I have never written a function in C. Before that manually Use the increasing allocation of and , thus I am afraid that there are still some quirks that need to be addressed so far
  • It seems that the code is actually Allocates more memory than needed Warnings reported by Valgrind Due to I have switched from malloc to calloc very bad
  • / code> one in code The place, which successfully deleted the warning, but I am not completely convinced that I am using it in the right way.

    This means that it allocates It is actually needed in comparison (using the 56k file):

      == 23668 == Heap Summary: Use == 23668 == 0 blocks on exit C = 0 2366 8 == Total Hep Usage: 49,998 Overall, 49,998 Free, 1,249, 875, 362 Bytes Allowed   

    ... This does not look right ...

    The question in the code is here (many of it & lt; Code & gt; to field on SO):

    Need help, and I'm grateful for any advice!

    The way you are moving your buffer is quite inefficient. For each small piece of string, you rehell () memory, which means that new memory is allocated and the contents of "old" memory are copied. It's slow and it's a piece of your heap.

    Increase in a good amount or a fixed percentage, i.e. size of the old size of 1.5 or 2 times. It also destroys some memory, but will not keep the pile more usable and many copies.

    This means that you have to keep track of two values: ability (number of bytes allocated) and length (the actual length of the string). But it should not be very difficult.

    I will present a function "FstrBuf_Grow" which takes care of everyone. You say it only with the amount of memory that you want to add, and FstrBuf_Grow will remember that the ability corresponds to the requirements of reallocation when needed, at least when needed.

      ... zero FstrBuf_Grow (FstringBuf * buf, size_t more) {While (buf-> Length + more) & gt; Buff- & gt; Capacity buff- & gt; Capacity = 3 * buf- & gt; Capacity / 2; Buf-> Data = reallock (buff- & gt; data, buff- & gt; capacity + 1); }   

    There is capacity up to 1.5 data in it, depending on your needs, you can select different strategies.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -