Почему вот этот код при декодировании закодированного файла добавляет лишних 5 байт и в конце вываливается с точкой останова на операторе delete?
#include "stdafx.h"
#include "COBS.h"
#include
#include <sys/stat.h>
unsigned RLEDeflate(const unsigned char* src, unsigned len, unsigned char* dst) {
unsigned out_pos = 0;
unsigned in_pos = 0;
while (in_pos < len) {
// Находим длину текущей последовательности одинаковых байтов
unsigned char current = src[in_pos];
unsigned run_length = 1;
while (in_pos + run_length < len &&
src[in_pos + run_length] == current &&
run_length < 255) {
run_length++;
}
// Если последовательность длинная (4+ байта), кодируем её
if (run_length >= 4) {
dst[out_pos++] = 0; // Маркер RLE-последовательности
dst[out_pos++] = run_length; // Длина последовательности
dst[out_pos++] = current; // Значение
in_pos += run_length;
}
else {
// Короткая последовательность - копируем как есть
for (unsigned i = 0; i < run_length; i++) {
// Экранируем случайные нули (хотя после COBS их не должно быть)
if (src[in_pos] == 0) {
dst[out_pos++] = 0;
dst[out_pos++] = 1;
dst[out_pos++] = 0;
}
else {
dst[out_pos++] = src[in_pos];
}
in_pos++;
}
}
}
return out_pos;
}
unsigned Size(const unsigned char* src, unsigned len) {
unsigned out_size = 0;
unsigned pos = 0;
while (pos < len) {
if (src[pos] == 0) {
// RLE sequence: 0 N b
out_size += src[pos + 1]; // N
pos += 3;
}
else {
// Single byte
out_size++;
pos++;
}
}
return out_size;
}
unsigned RLEInflate(const unsigned char* src, unsigned len, unsigned char* dst) {
unsigned out_pos = 0;
unsigned in_pos = 0;
while (in_pos < len) {
if (src[in_pos] == 0) {
// Проверка на достаточную длину буфера
if (in_pos + 2 >= len) { // Нужно 3 байта: 0 N b
cerr << "Invalid RLE sequence at end of file!" << endl;
break;
}
unsigned count = src[in_pos + 1];
unsigned char value = src[in_pos + 2];
// Проверка допустимости count
if (count < 4) { // RLE требует минимум 4 повторения
cerr << "Invalid RLE count: " << count << endl;
return 0;
}
for (unsigned i = 0; i < count; ++i) {
dst[out_pos++] = value;
}
in_pos += 3;
}
else {
dst[out_pos++] = src[in_pos++];
}
}
return out_pos;
}
int main()
{
try {
char cOperation;
cout << "Enter the first letter of the operation (c - compression; d - decompression):";
cin >> cOperation; cin.get();
if (cOperation != 'c' && cOperation != 'd') {
printf("Error: can't recognize this operation!...\n");
return -1;
}
string sFInName, sFOutName;
cout << "Enter name of Input File:" << endl;
getline(cin, sFInName);
cout << "Enter name of Output File:" << endl;
getline(cin, sFOutName);
// Определим размер файла в байтах
struct stat stat_buf;
int rc = stat(sFInName.c_str(), &stat_buf);
if (rc == -1) {
cout << "can't open '" << sFInName << "'" << endl;
return -1;
}
// Длина исходного буфера
unsigned int inLen = stat_buf.st_size;
// Выделим буфер под чтение файла
unique_ptr<unsigned char[]> buf(new unsigned char[inLen + 1]); // +1 для безопасности
// Прочтем файл в бинарной моде в буфер
ifstream ifs(sFInName, ios_base::binary);
if (!ifs.is_open()) {
cout << "can't open '" << sFInName << "' for reading" << endl;
return -1;
}
// Чтение с проверкой
ifs.read(reinterpret_cast<char*>(buf.get()), inLen);
if (ifs.gcount() != inLen) {
cout << "File read incomplete! Expected: " << inLen
<< ", read: " << ifs.gcount() << endl;
return -1;
}
ifs.close();
// Буферы для промежуточных результатов
// Для COBS: максимальный размер = исходный + ceil(размер/254) + 1
unsigned cobsMaxSize = inLen + (inLen / 254) + 2;
unique_ptr<unsigned char[]> tmp1(new unsigned char[cobsMaxSize]);
// Для RLE: в худшем случае размер увеличится в 3 раза
unsigned rleMaxSize = 3 * cobsMaxSize;
unique_ptr<unsigned char[]> tmp2(new unsigned char[rleMaxSize]);
unsigned char* outBuf = nullptr;
unsigned outLen = 0;
if (cOperation == 'c') {
// 1. COBS-кодирование
int cobsLen = COBSEncode(buf.get(), inLen, tmp1.get());
if (cobsLen <= 0) {
cout << "COBS encoding failed!" << endl;
return -1;
}
cout << "COBS encoded length: " << cobsLen << " (original: " << inLen << ")" << endl;
// 2. RLE-кодирование
outLen = RLEDeflate(tmp1.get(), cobsLen, tmp2.get());
unsigned estimatedSize = Size(tmp2.get(), outLen);
if (estimatedSize != cobsLen) {
cout << "RLE size mismatch! Expected: " << cobsLen
<< ", estimated: " << estimatedSize << endl;
}
outBuf = tmp2.get();
cout << "Compression stages:" << endl;
cout << "1. Original size: " << inLen << " bytes" << endl;
cout << "2. After COBS: " << cobsLen << " bytes ("
<< (100.0 * cobsLen / inLen) << "%)" << endl;
cout << "3. After RLE: " << outLen << " bytes ("
<< (100.0 * outLen / inLen) << "%)" << endl;
}
else {
// 1. Оценка размера декодированных данных
unsigned decodedSize = Size(buf.get(), inLen);
cout << "Estimated decoded size: " << decodedSize << endl;
// Проверка на слишком большой размер
if (decodedSize > rleMaxSize) {
cout << "Error: decoded size too large!" << endl;
return -1;
}
// 2. RLE-декодирование
outLen = RLEInflate(buf.get(), inLen, tmp1.get());
cout << "Actual RLE decoded size: " << outLen << endl;
// 3. COBS-декодирование
unsigned cobsDecodedSize = COBSDecode(tmp1.get(), outLen, tmp2.get());
outBuf = tmp2.get();
outLen = cobsDecodedSize;
cout << "COBS decoded size: " << outLen << endl;
// Проверка совпадения размеров
if (outLen != 110080) {
cout << "Warning: decoded size (" << outLen
<< ") doesn't match original file size (110080)!" << endl;
}
}
// Запись результата в файл
ofstream ofs(sFOutName, ios_base::binary);
if (!ofs.is_open()) {
cout << "can't open '" << sFOutName << "' for writing" << endl;
return -1;
}
ofs.write(reinterpret_cast<const char*>(outBuf), outLen);
if (!ofs) {
cout << "File write failed!" << endl;
return -1;
}
ofs.close();
cout << "Result successfully written to " << sFOutName << endl;
}
catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
return -1;
}
return 0;
}