I created the following function that takes all the elements of the square matrix to a vector of the appropriate size.The function works correctly with malloc, but I need to create the vector with posix_memalign and there the error occurs.
void convert_matrix_to_vector(int **matrix, const int matrixSize, int **vector, int *vectorSize){
int *vectorAux, i, j, k, vectorSizeAux;
vectorSizeAux = matrixSize * matrixSize;
posix_memalign((void **)&vectorAux, vectorSizeAux, vectorSizeAux * sizeof(int));
k = 0;
for (i = 0; i < matrixSize; i++){
for (j = 0; j < matrixSize; j++){
vectorAux[k] = matrix[i][j];
k++;
}
}
free_matrix_memory(matrix, matrixSize);
*vector = vectorAux;
*vectorSize = k;
}
When I run the program, the value of vectorSizeAux is 16.
The error that appears is: Program received signal SIGSEGV, Segmentation fault.
When trying to execute the line:
vectorAux[k] = matrix[i][j];
This answer is thanks to the user "Some programmer dude":
the POSIX reference page states that the alignment must be a power of 2 and also amultiple of sizeof(void*). If you're on a 64-bit system then sizeof(void*) will be 8 which makes 4 an invalid alignment.
That is why the minimum size for vectorSizeAux must be 8, and I got errors when running the program giving it values of 4, 8 and 16. In the value of 4, posix_memalign failed and the execution stopped and I no longer work with the other values.