It crashes with a debug error and says stack around variable 'code' was corrupted. This is code for a hamming code lab I am doing. The input file is just a bunch of 1's and 0's on the same line. Why is it crashing?
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];
}
There's two problems I see here:
It looks to me like you are calculating the size of the InMessage
buffer incorrectly in your hammingCode
function:
int len = strlen(InMessage), i = 0, j = 0;
The strlen
function determines the length of the string by finding the position of the first null terminator. If InMessage
is not cleared, then this could give you some strange lengths as it will contain a random sequence of bytes. Conversely, if you have cleared the buffer then len
will be 0.
To overcome this problem, it is better for the caller to provide the size of the buffer:
int hammingCode (char *InMessage, size_t messageSize)
And use messageSize
in place of len
.
It's advisable to use this same strategy for your other two functions as well as currently there is a chance of overflowing the provided buffers.
Following on from the previous problem, it may be that the decode
function is writing outside the bounds of the buffer. Providing the length of the buffer to decode
and adding the appropriate checks to ensure the function does not write outside the given bounds would be a good idea.