I have the following code that shows the dangers of using char arrays over strings:
int main(){
char password[] = "SECRET";
char msg[10], ch;
int i = 0;
cout << "Please enter your name:";
while((ch = getchar()) != '\n'){
msg[i++] = ch;
}
msg[i] = '\0';
cout << "\n\nHello " << msg << endl;
cout << "The password is " << password;
}
When I enter a name (stored in char msg[10]
) that is longer than 16 characters, everything after those 16 characters replaces the value stored in char password[]
("SECRET").
- Why is this the case? (a general curiosity)
- Why 16 characters and not 10 - the size of the array?
- Why is it always
password
that gets overwritten and not some other variable or some other part of the memory where I wouldn't notice immediately? - What's the benefit of using char[] over strings then?
EDIT: Updated with follow up questions:
5. In response to the argument that password
and msg
are declared next to each other, I shuffled the declaration block as follows:
char password[] = "SECRET";
char ch;
int i = 0;
char msg[10];
However, no change.
6. In response to the argument that it was chance that caused the gap between msg
and password
to be 6 (bytes?) long, I have recompiled the code many times, including the reshuffling above. Still, no change.
Any suggestions as to why?