【发布时间】:2015-06-20 02:39:30
【问题描述】:
我的代码出现分段错误,这是什么原因。
我认为这是因为 cur = readdir(dr); 中的 while 循环。当我尝试输入错误时,它没有进入 while 循环。
int main(char *source)
{
DIR *dr;
struct dirent *cur;
struct stat fi;
long int total_size = 0;
dr = opendir(source);
char *name=source;
size_t sourcelen = strlen(source);
printf("\n\n Source is %s\n\n\n", source);
printf("before *path \n");
char *path = malloc(100);
strcpy(path,source);
printf("before while \n");
while ((cur = readdir(dr)) != NULL)
{
if(cur->d_name[0] != '.')
{
free(path);
path = malloc(sourcelen + strlen(cur->d_name) + 2);
strcat(path,source);
strcat(path,"/");
strcat(path,cur->d_name);
if(stat(path, &fi) == -1)
{
printf("error \n\n");
}
else
{
printf("%s ",cur->d_name);
printf("%ld ",fi.st_blocks);
total_size = total_size + fi.st_blocks;
}
}
}
printf("\n\ntotal_size = %ld \n", total_size);
printf("\n\n\n");
}
【问题讨论】:
-
你可以注释掉什么并且仍然得到段错误?
-
你的 printf 处理了吗?你试过在调试器中运行它吗?
-
对于调试,确保
printf()格式字符串以换行符结尾很重要。如果他们不这样做,输出可能会被缓冲到很久以后。 -
在调试器中运行,获取导致段错误的LOC并不难。
标签: c segmentation-fault malloc readdir