I\'ve noticed that the string library doesn\'t require one to allocate space bef
ID: 658603 • Letter: I
Question
I've noticed that the string library doesn't require one to allocate space before writing the input/output. How does the string library allocate that memory dynamically, i know of the 'new' keyword in c++ and 'malloc' in c but when i try something like this, my program stops working.
char* str = new char[strlen(str) + 1];
cin>>str;
i can't get it to work that way, how does the string library work?
I also know of vectors in C++ but not a big fan of using them, i would like to know if there's a way to dynamically allocate memory without having to allocate a size before, something close but not as sophisticated as the string.h library.
How does the string library get unlimited input from user without the programmer specifying buffer size?
Explanation / Answer
How does std::string in c++ allocate memory?
as needed, transparently to the user.
i know of the 'new' keyword in c++ and 'malloc' in c but when i try something like this, my program stops working.
char* str = new char[strlen(str) + 1];
cin>>str;
Well ... yeah; strlen counts the consecutive characters at the provided address, until it encounters a zero. In your case, the specified address is not set (it will be set after strlen is evaluated) so you are effectively calling strlen with some random input - there is no way that would work.
I also know of vectors in C++ but not a big fan of using them,
You really really (really really really) should be. They are an extremely thin (read: fast) wrapper over creating dynamic contiguous memory blocks (exactly what you are trying to solve), that provide type safety, memory bounds safety and automatic memory management.
i would like to know if there's a way to dynamically allocate memory without having to allocate a size before
No.
something close but not as sophisticated as the string.h library.
The string.h is not able to allocate memory without knowing the size. It computes the size every time it needs to allocate memory, at a runtime cost (by, for example, using strlen when needed).
How does the string library get unlimited input from user without the programmer specifying buffer size?
It doesn't. What it does (in rough pseudocode) is this:
compute the size of the input (probably requesting it from the input steam through an API)
compute the new size the string should have after reading
allocate memory (depending on new size), if required
copy data in new memory
delete old memory and use new instead (if any old memory/value was set)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.