My code here-
void input(char* m)
{
char ch;
do
{
ch=getchar();
}
while(ch=='\n');
int i=0;
while(ch!='\n')
{
m[i++]=ch;
ch=getchar();
}
}
gives NZEC error. However, if I limit the input with a character count len , such as this-
void input(char* m, int len)
{
char ch;
do
{
ch=getchar();
}
while(ch=='\n');
int i=0;
while(ch!='\n'&&i<len-1)
{
m[i++]=ch;
ch=getchar();
}
}
it passes along fine. Why is that?
In the first case you have a buffer overflow !
Your while(ch!='\\n')
will loop until a '\\n' regardless of the number of chars typed in. If more chars are typed than there is space in the char buffer pointed to by m
, you might corrupt memory. Of course, in the second case, len
will avoid this.
Please note that in both cases, you do not ensure a null terminator to your buffer. So if you process youd m
as c-string you might also get not enough memory or a bufer overflow, as the string could be extremely long.
Have you ever considered defining your function as:
void input(std::string& m) {
// ...
m.push_back(ch); // instead of m[i++]=ch
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.