Search code examples
carrayspointersmemoryfunction-declaration

C Array/Pointer Argument Conversion


I have a generic problem solver written in C that takes an array of values and solves it in-place. The problem is taken in as a fixed-size array, and is then passed to a solving function. I ran into a strange performance issue when switching to using pointers instead of the fixed-size array.

The setup code follows:

int main() {
  int board[256];
  ...
  int *board2 = malloc(sizeof(int) * 256);
  memcpy(board2, board, 256);
  int result = solve_board(___);
}

I've tested the following declarations and calls (nothing else about the program changes):

// type 1 - fixed-size array
int solve_board(int board[256]);
solve_board(board);  // 1.167 seconds
solve_board(board2); // 3.760 seconds
// type 2 - pointer
int solve_board(int *board);
solve_board(board);  // 1.173 seconds
solve_board(board2); // 3.529 seconds

solve_board is partially recursive, so the call is made a large number of times during execution. Results are accurate for all cases.

Can anyone explain why using the dynamic array takes so much longer than passing along a fixed-sized array?


Solution

  • It is very likely that this is the problem:

    memcpy(board2, board, 256);
    

    This copies 256 bytes, not ints, from one array to the other. You probably mean:

    memcpy(board2, board, 256 * sizeof(int));
    

    So your two test cases were not running on the same data. The remaining (256 * (sizeof(int) - 1)) bytes of board2 were uninitialized and had garbage (= undefined) values.