I am trying to use memcpy
C library function to swap rows of 2D array(array of strings). Source files for this task is below:
main.c
#include <stdlib.h>
#include "main.h"
char *table[NBLOCK] = {
"abcdefghi",
"defghiabc",
"ghiabcdef",
"bcaefdhig",
"efdhigbca",
"higbcaefd",
"cabfdeigh",
"fdeighcab",
"ighcabfde",
};
int main() {
swap_rows(table, 0, 2);
return 0;
}
main.h
#define NBLOCK 9
#define BLOCK_CELLS 9
void swap_rows(char**, int, int);
shuffle.c
#include <string.h>
#include "main.h"
void swap_rows(char **table, int r1, int r2) {
char tmp[BLOCK_CELLS];
size_t size = sizeof(char) * BLOCK_CELLS;
memcpy(tmp, table[r1], size);
memcpy(table[r1], table[r2], size); /* SIGSEGV here */
memcpy(table[r2], tmp, size);
}
Segmentation fault occurs inside swap_rows
function. Out of three memcpy
calls shown above, the first one works as expected. I commented out the last two memcpy
calls and added below line:
table[0][0] = 'z';
But, segmentation fault occurred again. Why I am not allowed to override values of table
in swap_rows
function?