У меня есть куча коррупции и не могу найти причину. Пожалуйста, помогите? У меня есть некоторые фрагменты кода, где, на мой взгляд, ошибка расположена. коррупция кучи генерируется здесь (см комментарии ниже):куча коррупции. C
free(rowPermutation);
fclose(wFile);
Таким образом, распределение памяти здесь:
static int N = 2,**orderOfRows, *columnsPermutation,*tmpRowPermutation,*resultPermutation,
*u,*v,**sourceMatrix,**patternMatrix,**auxMatrix1,*incidence,*perm;
static FILE *wFile,*file,*patternFile;
void allocate2dMemory() {
int i = 0;
sourceMatrix = (int**) malloc(N * sizeof(int *));
auxMatrix1= (int**) malloc(N * sizeof(int *));
orderOfRows = (int**) malloc(N * sizeof(int*));
patternMatrix = (int**) malloc(N * sizeof(int*));
incidence = (int*) malloc(N * sizeof(int));
columnsPermutation = (int*) malloc(N * sizeof(int));
tmpRowPermutation = (int*) malloc(N * sizeof(int));
resultPermutation = (int*) malloc(N * sizeof(int));
perm = (int*)malloc(N * sizeof(int));
u = (int*) malloc(N * sizeof(int));
v = (int*) malloc(N * sizeof(int));
if ((sourceMatrix == NULL) || (auxMatrix1 == NULL) || (incidence == NULL) || (orderOfRows == NULL) ||
(columnsPermutation == NULL) || (tmpRowPermutation == NULL) || (u == NULL) || (v == NULL) || (resultPermutation == NULL)) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for (i = 0; i < N; i++) {
sourceMatrix[i] = (int*) malloc(N * sizeof(int));
auxMatrix1[i] = (int*) malloc(N * sizeof(int));
patternMatrix[i] = (int*) malloc(N * sizeof(int));
incidence[i] = 0;
if ((sourceMatrix[i] == NULL) || (auxMatrix1[i] == NULL) || (patternMatrix[i] == NULL)) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
}
Открытые файлы:
void openFile(char* filename) {
if ((file = fopen(filename, "r")) == NULL) {
perror("Open error");
printf("\nPress any key for exit\n\n");
getch();
exit(1);
}
if ((patternFile = fopen("pattern.dat", "r")) == NULL) {
perror("Open error");
printf("\nPress any key for exit\n\n");
getch();
exit(1);
}
if ((wFile = fopen("out.txt", "w")) == NULL) {
perror("Open error");
printf("\nPress any key for exit\n\n");
getch();
exit(1);
}
Тогда Я закрываю некоторые из них («wFile» - это файл для записи):
fclose(file);
fclose(patternFile);
Изменение строки заказа:
void changeRowOrder(int *computation,int **matr) {
fprintf(wFile,"Make row permutation\n");
int i,j;
for (i = 0; i < N; ++i) {
orderOfRows[computation[i]] = matr[i];
}
fputs("\n",wFile);
}
Изменить порядок столбцов:
int **destMatrix = (int**) malloc(N * sizeof(int *));
if ((destMatrix == NULL)) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for (i = 0; i < N; i++) {
destMatrix[i] = (int*) malloc(N * sizeof(int));
if (destMatrix[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
for(i = 0; i < N; ++i) {
// save permutation
resultPermutation[perm[i]] = i;
for(j = 0; j < N; ++j) {
destMatrix[i][j] = orderOfRows[i][perm[j]];
}
}
fprintf(wFile,"Now result permutation is: \n");
printArray(resultPermutation);
for(i = 0; i < N; ++i) {
free(sourceMatrix[i]);
}
free(sourceMatrix);
sourceMatrix = destMatrix;
мне нужно статические указатели, чтобы увидеть их во всей моей программе. Здесь находится другой код, где может существовать ошибка:
Код, приведенный в начале программы.
int res,i,j;
char c[25],f[25],g;
int *rowPermutation = (int*)malloc(N*sizeof(int));
openFile("inb.dat");
fscanf(file,"%s %s %d %d",&c,&f,&N,&i);
allocate2dMemory();
getMaxtrix();
// and so on ...
free(rowPermutation);
fclose(wFile);
Я не выделяю память в другом месте моей программы. Я заметил, что память повреждена в массиве «columnsPermutation». Во-первых, я копирую некоторые элементы, затем элемент начинает меняться. Я заметил это, когда я использовал контейнер STL для исправления кучи (просто чтобы узнать, почему массивы отличаются).
Пожалуйста, вы можете найти ошибку? На мой взгляд, я правильно распределяю память.
Можете ли вы дать нам точную ошибку на выходе? Вы пытались использовать GDB, чтобы найти что-нибудь? Кроме того, вы можете публиковать целые функции, а не только фрагменты? – samoz
Тангенциальный комментарий: [Вы должны предпочесть] (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) 'x = malloc (N * sizeof (* x))' к 'x = (T *) malloc (N * sizeof (T))'. –
Возможна опечатка в начале вашей программы. Возможно ли, что ваше имя функции 'getMatrix', а не' getMaxtrix'? – Marlon