【发布时间】:2012-03-28 05:38:29
【问题描述】:
我创建了一个函数,它创建一个具有动态字符串长度的动态字符串数组,然后我将它返回给我的主函数。在我的函数中一切正常,但是当我尝试在 main 中打印数组时,我在第 4 个字符串之后出现分段错误 - 前两个字符串也打印不正确。这部分程序应该找出目录及其子目录中的所有条目并将它们存储在主内存中。
结果如下:
Path[0]=A/New Folder. - i=0
Path[1]=A/atext - i=1
Path[2]=A/a - i=2
Path[3]=A/alink - i=3
Path[4]=A/afolder - i=4
Path[5]=A/afolder/set008.pdf - i=0
Path[6]=A/afolder/anotherfolder - i=1
Path[7]=A/afolder/anotherfolder/folderOfAnotherFolder - i=0
Path[8]=A/afolder/anotherfolder/folderOfAnotherFolder/mytext - i=0
Path[9]=A/afolder/anotherfolder/mytext - i=1
Path[10]=A/afolder/set001.pdf - i=2
Entries in directory: A
��
��
A/a
A/alink
Segmentation fault
这是代码: 功能:
char ** getDirContents(char *dirName,char **paths )
{
DIR * tmpDir;
struct dirent * entry;
//char tmpName[512];
char * tmpName=NULL;
struct stat node;
int size=0;
int i=0;
//paths=NULL;
if((tmpDir=opendir(dirName))==NULL){
perror("getDirContents opendir");
return NULL;
}
i=0;
while ((entry=readdir(tmpDir))!=NULL)
{
//if (entry->d_ino==0) continue;
if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)//Ignore root & parent directories
continue;but I
tmpName =(char *)malloc(strlen(dirName)+strlen(entry->d_name)+2);
strcpy(tmpName,dirName);
strcat(tmpName,"/");
strcat(tmpName,entry->d_name);
//printf("\ntmpName[%d]:%s",count,tmpName);
paths=(char**)realloc(paths,sizeof(char*)*(count+1));
paths[count]=NULL;
//paths[count]=(char*)realloc(paths[count],strlen(tmpName)+1);
paths[count]=(char*)malloc(strlen(tmpName)+1);
//memcpy(paths[count],tmpName,strlen(tmpName)+1);
strcpy(paths[count],tmpName);
printf("\nPath[%d]=%s - i=%d",count,paths[count],i);
count++;
if(lstat(tmpName,&node)<0)
{
printf("\ntmpName:%s",tmpName);
perror("getDirContents Stat");
exit(0);
}
if (S_ISDIR(node.st_mode))
{
getDirContents(tmpName,paths);//Subfolder
}
//printf("\n%s,iters:%d",tmpName,i);
free(tmpName);
tmpName=NULL;
i++;
}
close(tmpDir);
return(paths);
}
主要:
char **A=NULL;
count=0;
A=getDirContents(dir1,NULL);
Aentries=count;
count=0;
//B=getDirContents(dir2,NULL);
printf("\nEntries in directory: %s",dir1);
for(i=0;i<Aentries;i++)
{
printf("\n%s",A[i]);
}
count 是一个全局变量
我只是不知道出了什么问题,我想我正确地使用了 return 命令。我还尝试了将路径作为全局变量的相同代码,它运行良好(主要打印出正确的结果)。 我觉得这与我的函数的递归调用有关
【问题讨论】:
-
请把它归结为一个简单测试用例(不超过10-15行)。见sscce.org。
-
很好找到了。这真的是我的函数的递归调用我改变了这个:getDirContents(tmpName,paths);//子文件夹到那个:paths=getDirContents(tmpName,paths);//子文件夹现在可以正常工作了
标签: c arrays string function segmentation-fault