Challenge: std::string in C

Practice dynamic memory allocations by implementing a resizable string in C.

Problem statement

You want to implement a pseudo data structure for storing strings of arbitrary length. The advantage of your string data structure over raw C-style strings is that your data structure will be able to grow, without being limited to a fixed size.

For example, consider the following definition:

char str[256];

The string represented by str can store at most 255 characters and the null terminator. If more storage is needed (say 512 characters), the string can not be used.

To address this, you must implement a string that can resize itself when more space is needed.

The basic principle is the same as the principle behind std::string from C++. Don’t worry if you are not familiar with C++.

Implementation details

You’ll maintain a dynamically allocated string. The string will have an initial size of 10 and will grow when needed by doubling its size.

Note: Doubling the size when we’re out of space is a common implementation for containers such as std::vector or std::string. For example, for std::vector, this approach guarantees an amortized asymptotic complexity of ...