2017-10-10 45 views
1

我使用下面的代碼列出目錄中的文件,然後將它們放入一個名爲filename_list的長字符串中。該邏輯是在dir中列出文件名並將它們放入一個字符串 - 分段錯誤

  1. 使用的strdup(「」)的環路

  2. 之前分配一個零字符,空終止字符*使用的realloc()來做到這一點,其保留增加其大小在每個迭代現有的內容。我通過將舊的長度添加到文件名的長度來計算新緩衝區的時間。

  3. 我使用strcat()將文件名附加到緩衝區。

它工作正常,直到它試圖調用realloc()爲導致seg錯誤的最終文件名。

有人會知道我在做什麼錯嗎?是否會因最終0的長度沒有足夠空間而導致?

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


char *filename_list; 

int main(void) 
{ 
    DIR   *d; 
    struct dirent *dir; 
    d = opendir("/home/johnbrady/binary_test"); 

    char *start = ""; 
    filename_list = strdup(start); //allocate a zero-character null-terminated char* to begin with 
    int filename_list_length; 

    filename_list_length = strlen(filename_list); //get length of filename list length 
    printf("size of filename list length is %d\n", filename_list_length); //print size of filename list length 

    if (d) 
    { 
    while ((dir = readdir(d)) != NULL) 
    { 

     printf("\n***************************************************\n"); 
     printf("Getting next file\n"); 
     int filename_length = strlen(dir->d_name); //get length of the filename 
     filename_list_length = strlen(filename_list); //get length of filename 
     printf("The value of filename list length is now %d\n", filename_list_length); 
     printf("\nthe length of the next filename is %d\n", filename_length); 
     printf("The file name is: %s\n", dir->d_name); 

     printf("\nresize the memory block for the file name list to be %d\n", filename_length + filename_list_length); 
     realloc(filename_list, filename_length + filename_list_length); //reallocate size to accomodate new filename 

     strcat(filename_list,dir->d_name); //append new filename to existing one 
     printf("The filename list is now %s\n", filename_list);  
     filename_list_length = strlen(filename_list); //get length of filename 
     printf("size of filename list length is now%d\n", filename_list_length); 
    } 

    closedir(d); 
    } 


    return(0); 
} 
+0

'的realloc(filename_list,filename_length + filename_list_length);'=>'filename_list = realloc的(filename_list,filename_length + filename_list_length);' –

+0

[警告的可能重複:具有屬性聲明爲 'realloc的',的忽略返回值警告\ _unused \ _result](https://stackoverflow.com/questions/35190326/warning-ignoring-return-value-of-realloc-declared-with-attribute-warn-unused) –

+0

@ Jean-FrançoisFabre謝謝你或你的同類幫幫我。 –

回答

0

您還沒有分配的realloc()返回值(返回值: 的指針重新分配內存)。這是使用此功能時常見的錯誤。

更改此:

realloc(filename_list, filename_length + filename_list_length); 

這樣:

filename_list = realloc(filename_list, filename_length + filename_list_length); 

如果你啓用了警告編過,你會被你的朋友警告,編譯器:

警告:忽略'realloc'的返回值,d eclared屬性warn_unused_result [-Wunused-result] realloc(strp-> data,nbytes);

+1

非常感謝。傻我。 –

+0

不是真的@articsol,我前幾天做了同樣的錯誤,歡迎您! – gsamaras

+0

現在用你的金徽章你可以重複這個一式三份嗎? –

相關問題