2013-11-21 68 views
1

我有一個程序讀取文本文件並將其分離爲章節和段落結構。Glibc損壞的雙鏈表

struct paragraph 
{ 
    char** lines; 
    int numLines; 
}; 

struct chapter 
{ 
    struct paragraph** paragraphs; 
    int numParagraphs; 
}; 

struct book 
{ 
    struct chapter** chapters; 
    int numChapters; 
}; 

這裏是有問題的代碼片段,特別是realloc()的語句:

//int numChapters = -1; 
//char**** book = (void*)0; 
struct book* books = malloc(sizeof(struct book*)); 
books->chapters = malloc(sizeof(struct chapter)); 

books->numChapters = -1; 

//char*** nextChapter; 
struct chapter* nextChapter = malloc(sizeof(struct chapter)); 


while ((nextChapter = readChapter(bookFile))->paragraphs[0]) 
{ 
    if (++(books->numChapters) > 0) 
    { 
     books = realloc(books, sizeof(struct chapter*)*books->numChapters); 
     books->chapters[books->numChapters - 1] = nextChapter; 

    } 
} 
books = realloc(books, sizeof(struct chapter*)*books->numChapters); 
books->chapters[books->numChapters] = (void*)0; 

return books; 

稱爲此代碼段內的功能應能正常工作,至少我指望這個事實。這是一個存在管理不善的問題。感謝您的任何建議!

我應該提到,它讀通過前幾章,然後它得到的錯誤。

+0

實際上,我無法看到任何「[double-]鏈表」在哪裏.. – user2864740

+0

在if語句中執行realloc時會出現此錯誤。它看起來像是在內存或者類似的東西在閱讀前幾章之後。但是,有趣的是,刪除realloc語句完全允許我的程序讀取整個book.txt文件,但它不能正確存儲所有內容...。 – user2893045

+0

內存管理結構在realloc()之前已損壞。在valgrind下運行該程序。 – ninjalj

回答

1

也許你不需要在每個結構中使用兩次指針?你有章節的數組,段落 - 不需要使用兩次指針。

提供的代碼更可能使用數組,而不是列表。所以如果你正在嘗試使用列表 - 我在回答結束時提到了它們。否則,它是簡單修復它使用數組,這裏是第一個問題:

if (++(books->numChapters) > 0) 
{ 
    /* here books are reallocated */ 
    books = realloc(books, sizeof(struct chapter*)*books->numChapters); 
    /* but here chapters which had not been reallocated are acessed */ 
    books->chapters[books->numChapters - 1] = nextChapter; 

} 

如果你有一個新的篇章,那麼爲什麼你需要realloc的書嗎?只是realloc的書籍 - >章節:

if (++(books->numChapters) > 0) 
{ 
    books->chapters = realloc(books->chapters, sizeof(struct chapter*)*books->numChapters); 
    books->chapters[books->numChapters - 1] = nextChapter; 

} 

而在最後同一個問題:

/* books are reallocated, size is bad - reallocated to size of numChapters * (pointer size) */ 
books = realloc(books, sizeof(struct chapter*)*books->numChapters); 
/* perhaps access to non-allocated memory here */ 
books->chapters[books->numChapters] = (void*)0; 

應該是:

books->chapters = realloc(books->chapters, sizeof(struct chapter)*books->numChapters); 
// books->chapters[books->numChapters] = (void*)0; 

到最後一個元素分配NULL是不需要的,因爲章節的大小爲numChapters,並且訪問元素numChapters會導致訪問未分配的內存,崩潰。

以上所有代碼都使用數組的概念,而不是鏈接列表。

將其切換到鏈表有必要使用結構如下所示:

struct paragraph 
{ 
    struct paragraph *next; // <<-- this field is used to build 
          //  linked list of paragraphs 
    char* lines; 
    int numLines; 
}; 

struct chapter 
{ 
    struct chapter *next; // <<-- this field is used to build 
         //  linked list of chapters 
    struct paragraph* paragraphs; 
    int numParagraphs; 
}; 

struct book 
{ 
    struct chapter* chapters; 
    int numChapters; 
}; 

當然,適當的分配和需要的「下一個」指針賦值。

相關問題