簡體   English   中英

從文件中讀取二維數組,並在第一行中給出尺寸

[英]Read 2D array from file with dimensions given in the first line

我編寫了一個代碼,從文件中讀取第一行給出尺寸的2D整數數組。 在運行它時,出現以下錯誤:

*`./shell'錯誤:兩次釋放或損壞(輸出):0x000000000144a0c0 *已中止(核心已轉儲)

這是我的代碼

#include <stdio.h>
#include <stdlib.h>


int main(int argc , char* argv[])
{
FILE * fp;
char * line = NULL;
char * token ;
size_t len = 0;
ssize_t read;
int i;
int j ;
int flag = 0 ;
int row = 0 ;
int **matr ;
char cwd[1024];

getcwd(cwd, sizeof(cwd)) ;
char *matrix = malloc(strlen(cwd)+10);
// here but your file name

asprintf(&matrix,"%s%s",cwd,"/matrix");

fp = fopen(matrix, "r");
if (fp == NULL)
{
    exit(EXIT_FAILURE);
}

while ((read = getline(&line, &len, fp)) != -1)
{

    if(flag == 0)
    {
        token = strtok (line," ");
        i = atoi(token);
        token = strtok (NULL, " ");
        if (token != NULL)
        {
            j = atoi(token);

        }
        printf("%d   %d\n",i,j);
        flag =1 ;
        matr = (int**)malloc(i*sizeof(int*));
        int e ;
        for(e=0; e<=i; e++)
        {
            matr[e] = (int*)malloc(j*sizeof(int));
        }
    }

    else if(row <i)
    {
        int col = 0 ;
        token = strtok (line,"\t");
        while (token != NULL && col<j)
        {
            matr[row][col] = atoi(token);
            printf("%d ",matr[row][col]);
            col++ ;
            token = strtok (NULL,"\t");
        }
        printf("\n");
        row++ ;
    }

  }

fclose(fp);
return 0;
}

有什么辦法嗎?

發布的代碼具有無法恢復的內存泄漏。

通過調用malloc()函數將指針matrix設置為指向某些已分配的內存,

然后,該指針被對asprintf()的調用覆蓋,建議使用sprintf()或將對malloc()的調用替換為char *matrix = NULL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM