2013-05-02 38 views
0

我需要製作一個程序,首先從文本文件中讀取一個矩陣並將其放在內存中。我能夠這樣做,但是當我嘗試使用4行或更多行的矩陣關閉文件時,它會給出錯誤: * ./threads中的錯誤:損壞的雙向鏈表:0x0000000001b4e240 * 代碼讀取的文件是:*** ./threads中的錯誤:損壞的雙鏈表:0x00000000009bb240 *** in fclose

void leitura_matriz1() 
{ 
    char linha_s[MAX_LINHA]; 
    char *buffer; 

    // leitura da primeira matriz 
    FILE * matriz1_file; 
    matriz1_file = fopen ("in1.txt","r"); 
    if (matriz1_file == NULL) 
    { 
     printf ("Erro na abertura do arquivo\n"); 
     exit(1); 
    } 

    // número de linhas 
    fgets(linha_s, MAX_LINHA, matriz1_file); 
    buffer = strtok(linha_s, " ="); 
    buffer = strtok(NULL, " ="); 
    linhas_mat1 = atoi(buffer); 

    // número de colunas 
    fgets(linha_s, MAX_LINHA, matriz1_file); 
    buffer = strtok(linha_s, " ="); 
    buffer = strtok(NULL, " ="); 
    colunas_mat1 = atoi(buffer); 

    // aloca espaço para a matriz 
    matriz1 = (int**) malloc(linhas_mat1 * sizeof(int)); 
    if (matriz1 == NULL) 
    { 
     printf("erro memória"); 
     exit(1); 
    } 
    int lin, col; 
    for (lin = 0; lin < linhas_mat1; lin++) 
    { 
     matriz1[lin] = (int*) malloc(colunas_mat1 * sizeof(int)); 
     if (matriz1[lin] == NULL) 
     { 
      printf ("erro memória 2"); 
      exit(1); 
     } 
    } 

    // lê os valores do arquivo e coloca na matriz em memória 
    for (lin = 0; lin < linhas_mat1; lin++) 
    { 
     fgets(linha_s, MAX_LINHA, matriz1_file); 
     buffer = strtok(linha_s, " "); 
     for (col = 0; col < colunas_mat1; col++) 
     { 
      matriz1[lin][col] = atoi(buffer); 
      buffer = strtok(NULL, " "); 
     } 
    } 

    fclose (matriz1_file); 
} 

文件格式是這樣的:

LINHAS = 4 
COLUNAS = 3 
5 5 5 
5 5 5 
5 5 5 
5 5 5 

的linhas是線條和COLUNAS列 我從來沒有在關閉文件時,它仍然打開了錯誤。只有當文件有3行以上(4行或更多行)時纔會發生。有人知道它可能是什麼?

回答

2

第一次分配不正確。而不是:

matriz1 = (int**) malloc(linhas_mat1 * sizeof(int)); 

它應該是:

matriz1 = (int**) malloc(linhas_mat1 * sizeof(int*)); 

異常消息(8個字節)似乎表明在64位應用程序,所以指針將是8個字節,而sizeof(int)可能僅4個字節。這會在填充陣列時導致內存覆蓋。

+0

非常感謝。這似乎是問題所在。這是我第一次在64位操作系統中製作一個C程序,所以這種方法以前一直很有用。 – 2013-05-02 23:41:45