我使用下面的代碼列出目錄中的文件,然後將它們放入一個名爲filename_list
的長字符串中。該邏輯是在dir中列出文件名並將它們放入一個字符串 - 分段錯誤
使用的strdup(「」)的環路
之前分配一個零字符,空終止字符*使用的realloc()來做到這一點,其保留增加其大小在每個迭代現有的內容。我通過將舊的長度添加到文件名的長度來計算新緩衝區的時間。
我使用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);
}
'的realloc(filename_list,filename_length + filename_list_length);'=>'filename_list = realloc的(filename_list,filename_length + filename_list_length);' –
[警告的可能重複:具有屬性聲明爲 'realloc的',的忽略返回值警告\ _unused \ _result](https://stackoverflow.com/questions/35190326/warning-ignoring-return-value-of-realloc-declared-with-attribute-warn-unused) –
@ Jean-FrançoisFabre謝謝你或你的同類幫幫我。 –