C 堆栈周围变量已损坏
它因调试错误而崩溃,并表示围绕变量“code”的堆栈已损坏。这是我正在做的汉明密码实验室的代码。输入文件只是同一行上的一组1和0。为什么它会崩溃C 堆栈周围变量已损坏,c,stack,hamming-code,stack-corruption,C,Stack,Hamming Code,Stack Corruption,它因调试错误而崩溃,并表示围绕变量“code”的堆栈已损坏。这是我正在做的汉明密码实验室的代码。输入文件只是同一行上的一组1和0。为什么它会崩溃 void processFile(FILE* read, char* InMessage) { int i = 0, count = 0; for (i = 0; !feof(read); i++) { InMessage[i] = fgetc(read); count++; }
void processFile(FILE* read, char* InMessage) {
int i = 0, count = 0;
for (i = 0; !feof(read); i++) {
InMessage[i] = fgetc(read);
count++;
}
InMessage[count] = '\0';
}
void hammingCode(char* InMessage) {
int len = strlen(InMessage), i = 0, j = 0;
char code[12], temp[1000];
temp[0] = '\0';
for (i = 0, j = 0; i < len; i++, j++) {
code[j] = InMessage[i];
if (j == 10) {
j = 0;
decode(code);
code[11] = '\0';
strcat_s(temp, sizeof(char)*1000, code);
}
}
strcpy_s(InMessage, sizeof(char)*1000, temp);
}
void decode(char* codeWord) {
int i = 0, j = 0, parity[4] = {0}, diffParity[4] = {0}, twoPower = 0, readNSkip = 0, bitSum = 0;
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
for (j = twoPower; j <= 12; j++) {
if (readNSkip <= twoPower) {
if (j != twoPower) {
parity[i] += codeWord[j-2] - 48;
}
readNSkip++;
}
else {
if (readNSkip == twoPower*2)
readNSkip = 0;
readNSkip++;
}
}
if (parity[i] % 2 == 0)
parity[i] = 0;
else
parity[i] = 1;
if ((codeWord[twoPower-1] - 48) != parity[i])
diffParity[i] = 1;
}
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
bitSum += diffParity[i]*twoPower;
}
codeWord[bitSum] = !codeWord[bitSum];
}
void进程文件(文件*读取,字符*在消息中){
int i=0,count=0;
对于(i=0;!feof(read);i++){
InMessage[i]=fgetc(已读);
计数++;
}
InMessage[count]='\0';
}
无效汉明码(字符*InMessage){
int len=strlen(InMessage),i=0,j=0;
字符代码[12],温度[1000];
温度[0]='\0';
对于(i=0,j=0;i 对于(j=twoPower;j我在这里看到了两个问题:
在我看来,您的汉明码
函数中的InMessage
缓冲区大小计算不正确:
int len = strlen(InMessage), i = 0, j = 0;
strlen
函数通过查找第一个空终止符的位置来确定字符串的长度。如果未清除InMessage
,则可能会产生一些奇怪的长度,因为它将包含一个随机的字节序列。相反,如果已清除缓冲区,则len
将为0
为了克服这个问题,调用者最好提供缓冲区的大小:
int hammingCode (char *InMessage, size_t messageSize)
并使用messageSize
代替len
建议对其他两个函数使用相同的策略,因为目前有可能溢出提供的缓冲区
继上一个问题之后,可能是decode
函数正在写入缓冲区的边界之外。向decode
提供缓冲区的长度,并添加适当的检查以确保函数不在给定边界之外写入是个好主意
在调试器中运行代码时会发生什么情况?请尝试gdb./a.out,然后键入r并按enter键,然后查看它崩溃的原因..并修复它!