Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C dynamic string length

Tags:

c

string

dynamic

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.

like image 334
Luca Matteis Avatar asked Mar 22 '09 20:03

Luca Matteis


2 Answers

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).

like image 137
strager Avatar answered Sep 30 '22 01:09

strager


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

like image 22
tstenner Avatar answered Sep 30 '22 01:09

tstenner