比特打包和动态分配的问题

时间:2011-10-26 00:29:58

标签: c realloc bit-packing

我遇到了这段代码的问题。

我正在建立一个图像编码器。基本上我使用图像中的值构建了一个编码数组。该数组称为“代码”,并存储二进制值的char *表示。

此部分读取每个像素的灰度值,在“代码”数组中查找其值,并打包一个二进制值字节(tempString)。一旦读取了8个值,就成了tempString 被添加到已编码的无符号字节数组(encodedString)的末尾。

程序运行直到numBytes大约是27,000字节然后是seg fault。

我知道这是一个很长的镜头,但我希望它是如何分配内存的一个明显的问题。

    unsigned char* encodedString = malloc(1);
    unsigned char* tempString;
    encodedString[0] = '\0';

    unsigned char packedString = 0;
    int one = 1;
    int zero = 0;
    int width = image->width;
    int height = image->height;
    int row, col, count=0, numBytes=0; //numBytes is the number of already encoded bytes
    for(row = 0; row<height; row++)
    for(col = 0; col<width; col++)
    {
            int value = image->pixel[row][col];    //Gets the pixel value(0-255)
            char* code = codes[value];             //Gets the compression code for the color

            int length = strlen(code);

            for(index=0;index<length;index++)
            {
                    //This loop goes through every character in the code 'string'
                    if(code[index] == '1')
                            packedString = packedString | one;
                    else
                            packedString = packedString | zero;

                    count++;
                    if(count == 8)  //If 8 consecutive values have been read, add to the end of the encoded string
                    {
                            tempString = realloc(encodedString, (strlen(encodedString)+2));
                            if(tempString == NULL)
                                    return NULL;

                            encodedString = tempString;

                            //Add newly formed binary byte to the end of the already encoded string
                            encodedString[numBytes] = packedString;
                            //Add terminating character to very end             
                            encodedString[numBytes+1] = '\0';

                            count=0; //reset count
                            numBytes++;
                    }
                    else
                         packedString = packedString << 1;
            }

            *length_of_encoded_string += strlen(codes[value]);

    }

1 个答案:

答案 0 :(得分:0)

不要在二进制字符串上调用strlen(str)!请改用numBytesstrlen将返回 它在你的字符串中找到的第一个零的索引。然后realloc会停止增加字符串的大小,当您使用numBytes访问它时会导致段错误。

相关问题