You have fallen into an error that almost all programmers fall and most will continue to fall even knowing this because there is too much stubbornness. Now you can learn the correct way to learn programming. Never believe in tests to teach you something, believe in documentation and specification, that’s where it shows how something should be. Especially in C or C++ long ago undefined and unspecified behaviour what makes the result not help at all to define why something is working or is wrong, it may not even be so in another scenario. Plus you need to understand every detail of what you’re doing.
Did you know you’re not programming in C++? Of course, everything works on a C++ compiler, but it’s not idiomatic and it’s not just freshness to opt for the C++ language, it exists because it’s better than C, so you shouldn’t use malloc()
, unless it has a very strong justification. The same can be said for using a array of char
instead of using the type string
, where none of this would be happening.
One string of C, i.e., a array of char
has no size so to know when it should end need a terminator character, in case the null, where is the null there to know when to stop?
You are allocating 3 bytes (char
always has the size of 1 byte so it makes no sense to use sizeof
in it) and it is filling only 2 of these spaces, after all it is placing a character at position 0 and then at position 1, when the counter arrives at 2 it stops and therefore nothing is placed there. The third byte stays there with the trash that is in your memory and luck (or bad luck depending on the point of view because you can fool more looking like it’s right) if there is a null to terminate the string, otherwise it will close somewhere in the memory where find a byte 0, what happens will be coincidence and not the right.
By my understanding, the vector of char
has a minimum size
Only you know what this means, but it seems you don’t, there is no such concept that you think you have in the language. You’re using logic over misinformation, so you can’t hit it unless you’re lucky.
You are not putting the null terminator in the string, so the
&
that appeared in your tests is a mess of memory– Jefferson Quesado
Has more in this answer. I also made this research to search for an answer with this content, looking for the user with the greatest knowledge in C/C++ in the community
– Jefferson Quesado
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero