In the days before c++ and vector/lists, how did they expand the size of arrays when they needed to store more data?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Vector and list aren’t conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:
As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.
nothings/stb gives a simpler implementation that works with any types:
It also provides hash maps, and the trick it uses for type-safe containers in C can be applied to other generic containers too.
Any of these methods can expand the underlying storage either by a call to
realloc(see below), or by allocating new storage withmallocand freeing the old one withfree— which is equivalent to howstd::vectorgrows its memory in C++.A lot of C code, however, resorts to managing the memory directly with realloc:
Note that
reallocreturns null in case of failure, yet the old memory is still valid. In such a situation this common (and incorrect) usage leaks memory:Compared to
std::vectorand the C equivalents from above, the simplereallocmethod does not provide O(1) amortized guarantee, even thoughreallocmay sometimes be more efficient if it happens to avoid moving the memory around.