Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing string gives bytes C [duplicate]

When I write simple code to encode simple sequence of letters to bytes and decode again I have problem with decoding. Everything is going on by in finish I want to have sequence of 4 chars, but it includes also bytes on the end. Here is my code:

char* B2T(int num) {
    unsigned char temp;
    char res[4];
    int sw[] = { 6,4,2,0 };
    char tab[4] = { 'A', 'C', 'G', 'T' };
    int i = 0;
    for (int i = 0; i < 4; i++) {
        res[i] = tab[(num >> sw[i]) & 3];
    }
    printf_s("%s\n", res); //!!!!!!problem here!!!!!!!!
    return res;
}

int main() {
    FILE *I, *O;
    char tab[5], opt;
    int res, i, temp;
    bool work = true;
    while (work) {
        printf_s("\nChoose option: decode or encode (d/e): ");
        scanf_s("%c", &opt);
        switch (opt) {
        case 'e':
            fopen_s(&I, "DNA.txt", "r");
            fscanf_s(I, "%s", &tab, 5);
            fopen_s(&O, "result.bin", "a");
            while (feof(I) == 0) {
                res = T2B(tab);
                printf_s("%X ", res);
                fprintf_s(O, "%X ", res);
                fscanf_s(I, "%s", &tab, 5);
            };
            fclose(I);
            fclose(O);
            break;
        case 'd':
            fopen_s(&I, "result.bin", "r");
            fscanf_s(I, "%X", &temp);
            while (feof(I)==0) {
                char* ress = B2T(temp);
                fscanf_s(I, "%X", &temp);
            }
            fclose(I);
            break;
        }
    }
    return 0;
}
like image 893
daniktl Avatar asked May 08 '26 01:05

daniktl


1 Answers

You populate char res[4];, without null-terminating it, which causes Undefined Behavior, since printf() expects the null-terminating symbol to stop printing.

Do that instead:

char res[5];
res[4] = '\0';

Moreover, you should focus on this line:

while (feof(I) == 0)

which uses feof() inside a loop to stop parsing the file. This is a known issue, which explains your extra character. Please read Why is “while ( !feof (file) )” always wrong?


PS: In general all functions of the C library expect a string to be null-terminated, so it's strongly advised to have all your strings null-terminated.

like image 60
gsamaras Avatar answered May 10 '26 15:05

gsamaras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!