2011-10-26 3 views
0

임이 코드 조각에 문제가 있습니다.비트 패킹 및 동적 할당 문제

이미지 인코더를 만듭니다. 기본적으로 이미지의 값을 사용하여 인코딩 배열을 만들었습니다. 이 배열은 'codes'라고 불리며 이진 ​​값의 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]); 

    } 
+0

realloc을 27k 번 호출합니다. 그것은 정말로 좋은 생각처럼 보이지 않습니다. 현대적인 컴파일러/머신/OS로 메모리가 부족할 수도 있습니다. 이것은 아주 사소한 메모리입니다. 프로그램 시작시 32k를 단순히 mallocing하여 테스트 할 수 있습니다. 문제는 당신이 realloc 메모리 공간을 여러 번 호출하여 큰 덩어리가 남지 않았다고 생각하는 것일 수 있습니다. –

+0

고마워요. 제 컴퓨터가 처리 할 수있는 것과 똑같은 것을 가정했습니다. 나는 70k로 malloc을했고 괜찮 았어. –

답변

0

이진 문자열에 strlen(str)을 호출하지 마십시오. 대신 numBytes을 사용하십시오. strlen은 문자열에서 찾은 첫 번째 0의 색인을 반환합니다. 그러면 은 문자열의 크기를 늘리지 않고 numBytes을 사용하여 액세스 할 때 segfault로 이어집니다.