So, I'm trying to read a file of integers into 2 separate matrices. The first matrix is read in perfectly fine. Then the second one tries to read in from the file, gets to the last line and gets to a segfault. I have looked over the code about a bazillion times and can't figure out why I'm getting this segfault. Any help would be helpful!
Relevant code is pasted below:
int** allocation_matrix;
int** request_matrix;
allocation_matrix = (int **) malloc(num_processes * sizeof(int));
request_matrix = (int **) malloc(num_processes * sizeof(int));
for (i = 0; i < num_processes; i++)
{
allocation_matrix[i] = (int *) malloc(num_resources * sizeof(int));
request_matrix[i] = (int *) malloc(num_resources * sizeof(int));
}
for (i = 0; i < num_processes; i++)
{
for (j = 0; j < num_resources; j++)
{
fscanf(fp, "%d", &allocation_matrix[i][j]);
}
}
for (i = 0; i < num_processes; i++)
{
for (j = 0; j < num_resources; j++)
{
fscanf(fp, "%d", &request_matrix[i][j]);
printf("%d ", request_matrix[i][j]);
}
printf("\n");
}
num_processes * sizeof(int)
is the wrong size as the wrong type was used.
Instead of trying to use the right type with the pointer, determine the size based on the de-referenced pointer. Easier to code right, review and maintain.
// allocation_matrix = (int **) malloc(num_processes * sizeof(int));
allocation_matrix = malloc(sizoef *allocation_matrix * num_processes);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.