C dynamic string length

There are different ways to create dynamic strings in C (with constant duration). After some googling, the main way to do this is to use realloc () .

The method I implemented is using linked lists with 32 bytes for each node.

I was wondering if there are any more efficient ways to solve this problem besides using realloc () and linked lists, and what are the cons and pros for each method.

EDIT The reason I do this is because I get dynamic data from the recv () socket and looked for a flexible way to store it without allocating huge amounts of data, not needed.

+5
source share
4 answers

You can redistribute various predefined sizes. For example, when the buffer is full, double its size.

Using a linked list is a good idea, but the data is not continuous (for example, you cannot pass the whole structure to printf), and indexing requires more computation (O (N)). The main advantage is that the added lines (at both ends) are O (1).

+3
source

I think you're looking for Scatter-Gather I / O , the function you would be looking for would be readv () .

+2
source

realloc(), realloc, n O (n ^ 2) (realloc, , , .. , O (n)). - realloc, - O (n).

+1

Using 32 byte fragments means that the relationship between data and overhead is terrible - you have a pointer in a linked list and at least (maybe a lot more) the same one again from the memory allocator. I would strongly suggest allocating a much larger chunk of memory and growing exponentially in order to customize and see if this causes problems. Only if you have problems will I follow the link of the linked list.

+1
source

All Articles