2017-11-11 338 views
0

我在嘗試弄清楚如何爲這個結構分配和釋放內存時遇到了一些麻煩。分配這個嵌套結構的正確方法是什麼?

我需要使用它來創建FiniteTable在牛頓插值中使用。

typedef struct{ 
    unsigned int empty; 
    float value; 
}FiniteTableValue; 

第一種是一種具有真正價值的節點。

typedef struct{ 
    FiniteTableValue *column; 
    unsigned int length; 
}FiniteTableRow; 

FiniteTableRow保持FiniteTableValues的陣列。

typedef struct{ 
    FiniteTableRow *row; 
    unsigned int length; 
}FiniteTable; 

FiniteTable然後保持FiniteTableRows的陣列。

typedef struct{ 
    FiniteTable *tables; 
    unsigned int length; 
}FiniteTableList; 

FiniteTableList是FiniteTable的

我試着用的valgrind到debugg它的名單,似乎我一直訪問我沒有分配一些地址。

此外,這是正確的方式來釋放所有?

FiniteTableList *ftl ... 
    ... 
    for(int i = 0; i < ftl->length; i++){ 
    FiniteTable table = ftl->tables[i]; 
    for(int j = 0; j < table.length; j++){ 
     FiniteTableRow row = table.row[j]; 
     free(row.column); 
    } 
    free(table.row); 
    } 
    free(ftl->tables); 
    free(ftl); 
+0

valgrind錯誤是什麼?如果涉及未定義的數據,請嘗試使用'--track-origins = yes'運行。 –

+0

它對於「有條件的跳轉或移動取決於未初始化的值」我知道它們在哪裏,但我需要知道的只是如何簡單地通過malloc啓動所有這些結構 – Felipe

+0

在這種情況下,'--track-origins = yes'應該指向您需要修復的源代碼位置。如果沒有,您需要發佈valgrind錯誤和相應的源代碼。 –

回答

1

在您的解除分配的示例對象FtlFiniteTableList而非指針(FiniteTableList *)。我覺得你的意思寫:

FiniteTableList ftl ... 

要爲FiniteTableList結構分配內存你會做這樣的事情:

/* Assuming every table in the list will have num_rows rows and num_columns columns. */ 
FiniteTableList * 
allocate_table_list (int num_rows, num_columns, int num_tables) 
{ 
    FiniteTableList * res = malloc (sizeof *res); 
    res->tables = malloc (num_tables * sizeof (*res->tables)); 
    res->length = num_tables; 
    for (int t = 0; t < num_tables; t++) 
    { 
     FiniteTable table = res->tables[t]; 
     table.row = malloc (num_rows * sizeof (*table.row)); 
     table.length = num_rows; 
     for (int r = 0; r < num_rows; r++) 
     { 
      FiniteTableRow row = table.row[r]; 
      row.column = malloc (num_columns * sizeof (*row.column)); 
      row.length = num_columns; 
     } 
    } 
    return res; 
} 

如果你想零初始化你分配可以替代內存撥打電話malloccalloc

+0

當你做FiniteTableList * res = malloc(sizeof * res); ? – Felipe

+0

您正在爲頂層FiniteTableList對象分配內存。 (sizeof * res)表達式意思是「指針res指向的類型的大小」 – Kyrill

相關問題