【问题标题】:segmentation fault in my c code [closed]我的c代码中的分段错误[关闭]
【发布时间】: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


【解决方案1】:

你有:

int main(char *source)

这是对main() 的完全非正统且可能不受支持的定义。请参阅What should main() return in C and C++ 了解允许和不允许的完整故事。

几乎可以肯定,这也是您的分段错误的原因。你有:

DIR *dr;
…
dr = opendir(source);

您实际上有一个(小但非零)int 被视为(一部分?)char *,这将导致麻烦。

你需要:

int main(int argc, char **argv)
{
    if (argc != 2)
        …report error and do not continue…
    DIR *dr = diropen(argv[1]);
    …error check dr and continue if not null…

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多