0
我在代碼中出現段錯誤,原因是什麼。
我認爲這是因爲while循環cur = readdir(dr);當我試圖給出錯誤的輸入時,它不會進入while循環。我的C代碼中的段錯誤
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是否被處理?你有沒有試過在調試器中運行這個? – Dweeberly
爲了調試,確保您的'printf()'格式字符串以換行符結束很重要。如果他們不這樣做,輸出可能會被緩衝到很晚。 –