M main.c => main.c +2 -2
@@ 150,8 150,8 @@ struct Result read_data(char * filename) {
fseek(fptr, strip_offsets[i], 0);
unsigned char * other = malloc(strip_bytes[i]);
fread(other, sizeof(char), strip_bytes[i], fptr);
- int expected = expected_length(other, strip_bytes[i]);
- unsigned char * unpacked = unpack(other, strip_bytes[0], expected);
+ size_t expected = expected_length(other, strip_bytes[i]);
+ unsigned char * unpacked = unpack(other, strip_bytes[i], expected);
for (int j = 0; j < expected; j++) {
pixels[total_pointer] = unpacked[j];
total_pointer += 1;
M pack_bits.c => pack_bits.c +18 -10
@@ 1,37 1,45 @@
#include <stdio.h>
#include <stdlib.h>
-int expected_length(unsigned char hexArray[], int current_length) {
+size_t expected_length(unsigned char hexArray[], int current_length) {
+ /*
+ Compute the expected length of a resulting array after performing PackBits
+ decompression. This is necessary in order to allocate a suffciently large
+ buffer. PackBits is not efficient in all cases, and in some unlucky cases
+ the compressed array can be larger than the decompressed array.
+ */
int i = 0;
- int expected_size = 0;
+ size_t expected_length = 0;
while (i < current_length) {
int hex = hexArray[i];
if (hex > 128) {
hex = 256 - hex;
// Repeat the byte immediately after this one
// 256 - hex times
- for (int j = 0; j <= hex; j++) {
- expected_size += 1;
+ for (int j = 0; j <= hex; ++j) {
+ expected_length += 1;
}
i++;
}
else if (hex < 128) {
// Treat the next hex bytes as literal
- for (int j = 0; j <= hex; j++) {
- expected_size += 1;
+ for (int j = 0; j <= hex; ++j) {
+ expected_length += 1;
}
i += hex + 1;
}
i++;
}
- return expected_size;
+ return expected_length;
}
-unsigned char * unpack(unsigned char hexArray[], int current_length, int expected_legnth) {
+unsigned char * unpack(unsigned char hexArray[], int current_length, size_t expected_length) {
+ /*
+ Decompress a PackBits array
+ */
int i = 0;
- unsigned char * output = malloc(expected_length);
+ unsigned char * output = (unsigned char*) malloc(expected_length * sizeof(char));
int output_ptr = 0;
- int expected_size = 0;
while (i < current_length) {
int hex = hexArray[i];
if (hex > 128) {