Search code examples
cexc-bad-accessc-strings

Passing variable length array of c strings as function argument


In my main function, I declare a variable length array of c strings and then pass it into a function called secondPass()

In secondPass(), I run a loop that determines the contents of a string called dec_instruction, then I try to add it to my array.

int main(int argc, char *argv[]) {

    /* Logic to decide num_commands */

    char machine_instructions[num_commands][11];
    secondPass(machine_instructions, num_commands);
}


secondPass(char **machine_instructions, int num_commands){
    for(int i = 0; i < num_commands; ++i){
        char dec_instruction[11];

        /* Logic to decide contents of dec_instruction */

        strcat(machine_instructions[i], dec_instruction);
    }
}

Sorry I can't post the complete contents of my code. This is for a class project and the rules on sharing code are pretty strict.

Anyway, the strcat() line near the end throws EXC_BAD_ACCESS when on the second iteration, when i = 1. As far as I can tell, dec_instruction is a valid c string like any other. What's causing my error?


Solution

  • Argument char **machine_instructions does not denote a 2D-Array of type char[][11] but a pointer to a pointer to a char. This is often used as a pointer to an "array" of pointers, but it is never an array of arrays of chars.

    So in your code, machine_instructions[i] will try to dereference a pointer to char, but the content you pass consists of plain characters and not of pointer values. Therefore the BAD_EXCESS.

    Using char machine_instructions[][11] should solve the problem.