There are different ways of creating dynamic strings in C (with length that constantly changes). After some google search, the main way of doing this is to use realloc().
A way I implemented this is using linked lists with 32 bytes chunks for each node.
I was wondering if there are better ways of tackling this apart from using realloc() and linked lists, and what the cons and pros for each method are.
EDIT The reason I am doing this is because I'm receiving dynamic data from a socket recv(), and was looking for a flexible way of storing it, without allocating huge amounts of data that aren't needed.
You can realloc to different 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 (you can't pass the whole structure to printf
, for example) and indexing takes more calculations (O(N)). A major advantage is that appending strings (at either end) is O(1).
I think you're looking for Scatter-Gather I/O, the function you'd be looking for would be readv().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With