0

I am writing a code, I have a two dimensional char array:

char *encode(char *text, size_t rails) {
char **format = calloc(rails, sizeof(char*));
char *cipherText = calloc(strlen(text), sizeof(char*));
size_t row, column, i;

for (i = column = 0; i < strlen(text); column++) {
    for (row = 0; row < rails; row++, i++) {
        format[row] = realloc(format[row], sizeof(char) * (column + 1));//works
        format[row][column] = text[i];
    }
    
    column++;
    for (row = rails-1; row >= 0; row--, i++) {
        format[row] = realloc(format[row], sizeof(char) * (column + 1));//this causes segmentation fault
        format[row][column] = text[i];
    }
}

Any why does the realloc causes this in the second time if it's the exact same of the last time

  • 3
    The control expression in your second `for` loop (`row >= 0`) will never be false, because `row` is an ***unsigned*** type. Thus, the loop will run forever and, on the loop after `row` reaches zero, that will roll over and you will be trying to access an out-of-bounds element of the `format` array. – Adrian Mole Nov 18 '22 at 14:16

0 Answers0