Search code examples
cstringsubstring

Having issues splitting string into chunks in C for cipher project


I'm working on a cybersecurity program where I need to split a string of plaintext into blocks of a certain size. The code I currently have does not work but is close. Certain letters are either skipped, or the blocks end up being larger than the block size. Additionally, characters appear that are not represented in the plaintext, but I am unsure of how this could even occur. Could anyone fix this code for me or illuminate where I am going wrong?

Example plaintext: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz

Example output:

Output

In the following code, plaintext_len_no_pad is the string of plaintext I want to break into chunks of size size. The size in this case is 2.

    // Split plaintext into blocks size n
    int total_blocks = plaintext_len_no_pad / size;
    printf("DEBUG Total blocks: %d\n", total_blocks);
    char blocks[total_blocks][size + 1];
    int k = 0;
    for (int i = 0; i < total_blocks; i++)
    {
        for (int j = 0; j < size; j++)
        {
            blocks[i][j] = plaintext_no_pad[j + k];
        }
        blocks[i][k + 1] = '\0';
        k += size;
    }
    for (int i = 0; i < total_blocks; i++)
    {
        printf("DEBUG Block %d: %s\n", i, blocks[i]);
    }

I've tried adjusting where I put the string terminating character, and messed with different ways of splitting the string. This method I whipped up has a bug I cannot figure out. I have looked at related posts, but I have not found one that helped.


Solution

  • blocks[i][k + 1] = '\0';
    

    is most definitely not right.

    The first iteration of the outer loop it will be equivalent to blocks[i][1]. The second iteration it will be equivalent to blocks[i][size + 1] which is out of bounds. Then it get further out of bounds.

    You should be using

    blocks[i][size] = '\0';
    

    instead.


    Also be careful if plaintext_len_no_pad is not evenly divisible by size (i.e. when plaintext_len_no_pad % size != 0).