From the code shown here, and given the error, it looks like you have an out of bounds array access somewhere that is corrupting malloc's own data structures.
The fact that it works with some files is sheer luck, that's the problem with undefined behaviour - behaving like expected is a form of undefined behaviour, this is what makes bugs like these hard to track.
From what I can see here, this is wrong:
while (Counter < FileSize)
{
Character = fgetc(File);
sprintf(HexArray + Counter, "%c", Character);
Counter++;
}
HexArray
is a dynamically allocated array of FileSize
bytes. However, note that sprintf()
always terminates the output string with a null-byte. Thus, for each iteration, HexArray[Counter]
is set to Character
, and HexArray[Counter+1]
is set to a null byte. There's no harm in this except in the last iteration. When Counter
is FileSize-1
(the last iteration), sprintf()
will be writing a null byte into HexArray[FileSize]
- out of bounds access. This is undefined behaviour and will most likely corrupt malloc data structures, thus yielding the cryptic errors later in the program.
If all you want to do is to write a character to each position in HexArray
, you can use the much more efficient and less error-prone form:
while (Counter < FileSize)
{
Character = fgetc(File);
HexArray[Counter++] = Character;
}
Also, since Character
is unsigned char
, you should change HexArray
from char *
to unsigned char *
.
Consider also what happens with huge files (if your program is supposed to be invoked with those). Memory exhaustion is a reality, especially if you're developing for an embedded system (which seems to be the case).