I'm trying to write a compressed bits matrix to a and the read it back. The writing works great but the reading keeps failing and I dont understand why.
typedef unsigned char BYTE;
int saveCompressImageToFile(const char *fileName, const int *image, int row, int col)
{
FILE *fp = fopen(fileName, "wb");
if (!fp)
return 0;
if (fwrite(&row, sizeof(int), 1, fp) != 1) {
fclose(fp);
return 0;
}
if (fwrite(&col, sizeof(int), 1, fp) != 1) {
fclose(fp);
return 0;
}
int byteCount = row * col / 8;
if (byteCount * 8 < row * col)
byteCount++;
BYTE *data = (BYTE *)calloc(sizeof(BYTE), byteCount);
int dataPos;
int dataShift;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
dataPos = (i * col + j) / 8;
dataShift =7 - (i * col + j) % 8;
data[dataPos] |= (*(image + i * col + j)) << dataShift;
}
}
if (fwrite(data, sizeof(BYTE), byteCount, fp) != byteCount) {
fclose(fp);
return 0;
}
return 1;
}
int * getImage_compress(const char * fileName, int * pRow, int * pCol)
{
FILE* fp = fopen(fileName, "rb");
if (!fp)
return NULL;
if (fread(pRow, sizeof(int), 1, fp) != 1)
{
fclose(fp);
return NULL;
}
if (fread(pCol, sizeof(int), 1, fp) != 1)
{
fclose(fp);
return NULL;
}
size_t mat_size = *pRow * (*pCol);
int byteCount = mat_size / 8;
if (byteCount * 8 < mat_size)
byteCount++;
BYTE* data = (BYTE*)malloc(sizeof(BYTE)*byteCount);
if (!data)
{
fclose(fp);
return NULL;
}
if (fread(data, sizeof(BYTE), byteCount, fp) != byteCount)
{
free(data);
fclose(fp);
return NULL;
}
fclose(fp);
int* mat = (int*)calloc(mat_size, sizeof(int));
if (!mat)
{
free(data);
fclose(fp);
return NULL;
}
for (int i = 0; i < mat_size; i++)
{
for (int j = 0; j < 8; j++)
{
mat[i * 8 + j] = (data[i] >> (7 - j)) & 0x1;
}
}
free(data);
return mat;
}
for some reason the function throws exception in the last line (return mat;) , "Starter.exe has triggered a breakpoint". occurred , what's going on over there? I've tried to debug that code and I can't tell why I can't return this value but I can access the cells in the debugger. any Suggestions?