“周围的变量堆栈被损坏”错误

问题描述:

我试图读取使用与fgets如下char值:“周围的变量堆栈被损坏”错误

int main() { 
    char m_cityCharCount; 

    // Input the number of cities 
    fgets(&m_cityCharCount, 4, stdin); 
    return 0; 
} 

Visual Studio中返回该错误代码被执行后 - Stack around the variable m_cityCharCount was corrupted

是有什么我可以做的呢?

+0

大小char'的'是在C 1,不4.修改的示例:'炭m_cityCharCount [16];与fgets(m_cityCharCount,的sizeof m_cityCharCount,标准输入);'' – BLUEPIXY

+1

fgets'旨在读零结尾*字符串*。您正在使用一个“char”作为接收缓冲区,它只对一个空的以零结尾的字符串足够。在做这件事的时候,你用'4'来骗'fgets'。您的接收缓冲区只包含'1'' char',而不是'4'。 – AnT

第一个参数是缓冲区指针(它的尺寸要大或等于比第二个参数的sizeof,但(焦)== 1)。

int main() { 
    char m_cityCharCount[4]; 

    // Input the number of cities 
    fgets(m_cityCharCount, 4, stdin); 
    return 0; 
} 

m_cityCharCount是一个字符,它最多可以容纳一个字符,但你告诉fgets它是4字节缓冲区。即使您只输入了回车键,fgets也会将新行和空终止符存储到缓冲区,这是造成严重问题的原因。你需要一个更大的缓冲做fgets:与fgets()的

char str[4096]; 
fgets(str, sizeof str, stdin);