Reputation: 2438
I'm trying to read a char value using fgets as follows:
int main() {
char m_cityCharCount;
// Input the number of cities
fgets(&m_cityCharCount, 4, stdin);
return 0;
}
Visual Studio returns this error after the code is executed - Stack around the variable m_cityCharCount was corrupted
Is there something I can do about it?
Upvotes: 2
Views: 1214
Reputation: 1121
First parameter of fgets() is pointer on buffer (size of it should be great or equals than second parameter. But sizeof(char) == 1)
int main() {
char m_cityCharCount[4];
// Input the number of cities
fgets(m_cityCharCount, 4, stdin);
return 0;
}
Upvotes: 1
Reputation: 13786
m_cityCharCount
is a char, it can hold one char at the most, but you are telling fgets
it is 4 bytes buffer. Even if you input nothing but hit the enter key, fgets
will store the new line AND the null terminator to the buffer, which of cause is a serious problem. You need a bigger buffer to do fgets
:
char str[4096];
fgets(str, sizeof str, stdin);
Upvotes: 2