My goal here is to read characters from std::cin and store it in an allocated array until an '!' is read.
My code works just fine until I reach about 8 characters read, and then it starts producing erroneous characters. Can someone tell me what's going on here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int size = 0;
char* str = newchar[size];
for(char ch; cin >> ch && ch != '!';) {
size++;
char* temp = str;
str = newchar[size];
//copy old string into new string
for(int i = 0; i < size-1; ++i) {
str[i] = temp[i];
}
delete[] temp;
//append ch to our string
str[size-1] = ch;
std::cout << str << '\n';
}
I don't see anything obviously wrong with your code.
Note that the >> operator ignores whitespace characters. If you want your string to contain whitespace characters you might want to use cin.get(ch); instead.
Unlike operator<< for regular strings, operator<< for C's char* will keep reading characters from memory and printing them until it encounters a zero. Which isn't there.
Unlike operator<< for regular strings, operator<< for C's char* will keep reading characters from memory and printing them until it encounters a zero. Which isn't there.
You we're right. This fixed the problem. My question now is, why did it work with the first few characters?
My question now is, why did it work with the first few characters?
Totally by accident. You'd be surprised how often this happens, even with commercial software. In this case, maybe the OS clears memory before allocating it to the heap. That would make sense for security reasons if you think about it. So the first few new's might get zero-initializes (and zero-terminated) memory. After you delete a few arrays, the memory gets reused.
But that's just idle speculation. The point is that if you don't explicitly zero-terminate the string then there's no telling whether it will work.