vendredi 8 mai 2015

Same code, same input, but randomly different output? (memcpy related)

I have this code which is supposed to decode a string (tmp) that contains only 0s and 1s (each ASCII character has a binary code asigned). The problem is that if I run the program with the exact same input, the output is different after the first 10 decodes.

tmp[500] = "110100110111110110110001110000110011110010111101001010001000111001111010000000000100011100100011110011010011001001101001100011100100010111111011010100000100100110010111011010010101110101101000010100111000101011001011111011101010001010111010100110000111101000110111001000000101000101011001011001001111110010010010110110110110101111001111101110001110110000";
char code[256][100];
int of=0;
char new_text[100];
char *buffer;
buffer = (char*) malloc (sizeof(char));
int buffer_size, j;
for (j=0; j<256; j++) {
    buffer_size = strlen(final_code[j]);
    free(buffer);
    buffer = (char*) malloc (buffer_size+1);
    memcpy(buffer, tmp, buffer_size);
    buffer[buffer_size]=0;
    if (strcmp(buffer, code[j]) == 0) {
        new_text[of++] = j;
        printf("It's a Match! buffer=%s, code[%d]=%s\n", buffer, j, code[j]);
        break;
    }
}
strcpy(tmp, tmp+buffer_size);

(It is guaranteed that the encodings do not 'conflict', most of them have the same number of characters and there aren't codes with the same beggining, like '0001' and '00010'.)

I suspect the problem is related to the memcpy, but I can't see it. Also, when crashing, the value of buffer_size is 5, but strlen(buffer) is 6, which might be the error source. Any ideas?

Aucun commentaire:

Enregistrer un commentaire