0

In c-strings we need to allocate reasonable size of memory. To avoid reallocations in string operations, we can use something like Stringbuilder in C# or Java or - in C - just allocate more memory for string. But still it can be a problem if we don't know the memory requirement in advance. Do we have some implemetation like linked list? I mean to allocate list of blocks of memory and method c_str() which creates c-string from its nodes

liststring a(4); // requested block size
a.append("hello ");
a.append("world");
// should create three nodes, 4 bytes allocated for each
// "hell" -> "o wo" -> "rld"
a.c_str(); // "hello world";

Or do we use another approach if we want to avoid reallocations? Please explain if it is bad idea.

3
  • When you invoke c_str(), you will need to put the string into a contiguous memory buffer anyway, so it's generally held that it's a good idea to do so from the start. Using a linked list of fixed sized blocks also means that building up a long string will spend O(n) in allocations, whereas the usual exponential increase allocation strategy for strings spends O(log(n)) at the cost of wasting more memory. Commented Feb 23, 2012 at 19:48
  • But if we want to append many times and we don't know how many and what size, we may allocate too few bytes (so need to reallocate) or too many (waste of memory). Commented Feb 23, 2012 at 19:53
  • There are an algorithm guarantees not to use memory more than four times of string length and each reallocate takes O(1) time on average. If the current size of buffer is n and the length of the string is out of buffer, then buffer of 2*n size should be reallocated. If it became less then n / 4 then buffer of n / 2 size should be reallocated. Commented Feb 23, 2012 at 20:01

3 Answers 3

3

See the article on Ropes for a data structure that keeps strings as trees. It is similar to your idea.

Sign up to request clarification or add additional context in comments.

Comments

0

There are no standard ways to do this. But you can implement your own linked list of chars and conversion to C string.

Comments

0

I am assuming you meant C++, not C.

The standard class for string manipulation in C++ is std::string.

String classes in Java or .NET are immutable. std::string on the other hand is mutable, so it is behaving exactly like StringBuilder.

2 Comments

No, I mean C, but C++ would be also fine. std::string does not provide the functionality I want. Or does it?
Probably not, as all implementations I know are contiguous in memory. See AShelly's answer: it is what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.