c - Why am I getting a segfault here? -
code split data training / test subsets below. note data_points 1 long vector of size items*attr, , data_labels vector of size items.
int split_data(int items, int attr, double *data_points, int *data_labels, double **split_train_points, int **split_train_labels, double **split_test_points, int **split_test_labels) { srand(time(null)); int i, j; double temp0, temp1; double sorter[items][2]; *split_train_points = malloc(floor(split_prop*items * attr) * sizeof(double)); *split_train_labels = malloc(floor(split_prop*items ) * sizeof(int)); *split_test_points = malloc(ceil((1-split_prop)*items * attr) * sizeof(double)); *split_test_labels = malloc(ceil((1-split_prop)*items ) * sizeof(int)); // create 2d array element number in 1 column , random number in other (i = 0; < items; i++) { sorter[i][0] = i; sorter[i][1] = rand() / (double)rand_max; } // sort random number column (i = items-1; > 0; i--) { (j = 1; j <= i; j++) { if (sorter[j-1][1] > sorter[j][1]) { temp0 = sorter[j-1][0]; temp1 = sorter[j-1][1]; sorter[j-1][0] = sorter[j][0]; sorter[j-1][1] = sorter[j][1]; sorter[j][0] = temp0; sorter[j][1] = temp1; } } } int cutoff = floor(split_prop*items); int element = 0; // have bunch of indices in random order. select first 70% store our split_train datasets (i = 0; < cutoff; i++) { element = (int)sorter[i][0]; *split_train_labels[i] = data_labels[element]; printf("success!\n"); (j = 0; j < attr; j++) { printf("j: %d, data_points_element: %d\n",j,attr*element+j); //segfault occurs here when j=4 every time element value changes due randomness *split_train_points[attr*i+j] = data_points[attr*element+j]; printf("j out! %d\n",j); } } (i = cutoff; < items; i++) { *split_train_labels[i - cutoff] = data_labels[(int)sorter[i][0]]; (j = 0; j < attr; j++) { *split_train_points[attr*(i-cutoff)+j] = data_points[attr*(int)sorter[i][0]+j]; } } return 0; }
as noted in code, segfault occurs @ same line, @ j=4, though "element" random number.
my guess it's because expression *split_train_labels[i]
doesn't mean think means. compiler same *(split_train_labels[i])
, mean (*split_train_labels)[i]
. have problem in multiple places.
array indexing has higher precedence pointer dereference.