0

我对这段代码有问题。

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

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

程序运行到 numBytes 大约为 27000 字节,然后出现段错误。

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

    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]);

    }
4

1 回答 1

0

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

于 2011-10-26T06:23:49.710 回答