免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3967 | 回复: 3
打印 上一主题 下一主题

[C] 程序运行中突然中止,求指点。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-12-31 21:59 |只看该作者 |倒序浏览
程序如下:
/* pw1_30.c an implementation of the 'pwd' utility
* features:
* usage:
* building:
*/
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<string.h>
#define RLEN 32
#define CLEN 256
static int i=0;
char dirname_arr[RLEN][CLEN]={0};
void do_pwd()
{
        struct stat stat_st;
        stat(".",&stat_st);
        DIR * dir_p=opendir("..";
        struct dirent * dirent_pst;
        ino_t temp1=0,temp2=1;
        char tempname_arr[CLEN];
        int flag=0;
   for(;
   {
        dirent_pst=readdir(dir_p);
        if(strcmp(dirent_pst->d_name,"."==0)temp1=dirent_pst->d_ino;
        if(strcmp(dirent_pst->d_name,".."==0)
        {
                temp2=dirent_pst->d_ino;
                strcpy(tempname_arr,dirent_pst->d_name);
                flag=1;
        }
        if((dirent_pst->d_ino==stat_st.st_ino)&&(flag==1))
        {
                //dirname_arr[0]=dirent_pst->d_name;
                free(&stat_st);
                i++;
                //printf("i=%d\n",i);
                sprintf(dirname_arr[i],"/%s",dirent_pst->d_name);
                //printf("path:%s\n",dirname_arr[i]);
                chdir(tempname_arr);
                free(dirent_pst);
                do_pwd();
        }
        if(temp1==temp2)
        {
                for(;i>=0;i--)
                {
                        printf("%s",dirname_arr[i]);
                }
                printf("\n";
                exit(0);
        }
   }
}
int main()
{
        do_pwd();
        return 0;
}

论坛徽章:
0
2 [报告]
发表于 2013-12-31 23:18 |只看该作者
没有用过这个API,也没有试过,单纯目测,有点疑问(man readdir)
1.
dirent_pst=readdir(dir_p),如果没有成功,返回一个NULL,而你没有检查直接使用,那么这里会导致CRASH。
2.
根据 man readdir, 上面明显表示不要free()返回值。。。。

仅供参考。

论坛徽章:
0
3 [报告]
发表于 2013-12-31 23:22 |只看该作者
建议strace一下。。。
很快就可以看到在什么地方挂掉了。。

论坛徽章:
0
4 [报告]
发表于 2013-12-31 23:30 |只看该作者
另外,直接在API中  exit(0);
这个做法好像一般不鼓励吧。。

坐等大牛分析。。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP